Lokathor / bytemuck

A crate for mucking around with piles of bytes
https://docs.rs/bytemuck
Apache License 2.0
697 stars 77 forks source link

Casts and conversions for owned, boxed slices #238

Open Pr0methean opened 4 months ago

Pr0methean commented 4 months ago

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:

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

zachs18 commented 4 months ago

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

Pr0methean commented 4 months ago

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

Pr0methean commented 4 months ago

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

Lokathor commented 4 months ago

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?

Pr0methean commented 4 months ago

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.