bytemuck icon indicating copy to clipboard operation
bytemuck copied to clipboard

Casts and conversions for owned, boxed slices

Open Pr0methean opened this issue 9 months ago • 5 comments

Owned slices can be cast with fewer restrictions than mutably borrowed ones, because the cast doesn't have to be reversible. This issue is a request for two features:

  • try_cast_boxed_slice: casts Box<[A]> to Box<[B]> if they have the same layout and B is AnyBitPattern.
  • convert_boxed_slice: converts Box<[A]> to Box<[B]> if they have the same layout, and takes a Fn(A) -> B parameter. (Could be implemented by first casting to a slice of a union type.)

An example use case for convert_box_slice would be to create a safe version of this function, although it would also require ColorU8, the output type, to implement AnyBitPattern. Note that the input type PremultipliedColorU8 cannot implement AnyBitPattern, since it has the invariant that no color byte has a larger value than the alpha byte. ColorU8 can implement AnyBitPattern but doesn't.

https://github.com/Pr0methean/OcHd-RustBuild/blob/main/main/src/image_tasks/png_output.rs#L312-L324

Pr0methean avatar May 05 '24 23:05 Pr0methean

Does bytemuck::allocation::(try_)cast_slice_box (requires the extern_crate_alloc cargo feature) do what you need for the first point?

zachs18 avatar May 05 '24 23:05 zachs18

Yes, that looks like it would work. Testing it with a clone of ColorU8 that derives Pod...

Pr0methean avatar May 05 '24 23:05 Pr0methean

Confirmed that it works and requires only one transmute inside the loop: https://github.com/Pr0methean/OcHd-RustBuild/blob/ba81f122e912db489dfb292269caae492eff5c15/main/src/image_tasks/png_output.rs#L313-L326

Pr0methean avatar May 06 '24 02:05 Pr0methean

So just the "convert" is still requested.

When you say that "A and B have the same layout" you mean just size/align so that the slice of target B will have the same elements as the source A?

Lokathor avatar May 06 '24 06:05 Lokathor

Yes, that's right. In fact, having the same padded size would probably be enough; and with allocator_api a smaller padded size would be an option.

Pr0methean avatar May 06 '24 06:05 Pr0methean