Open Pr0methean opened 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?
Yes, that looks like it would work. Testing it with a clone of ColorU8
that derives Pod
...
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
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?
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.
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
: castsBox<[A]>
toBox<[B]>
if they have the same layout and B isAnyBitPattern
.convert_boxed_slice
: convertsBox<[A]>
toBox<[B]>
if they have the same layout, and takes aFn(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 requireColorU8
, the output type, to implementAnyBitPattern
. Note that the input typePremultipliedColorU8
cannot implementAnyBitPattern
, since it has the invariant that no color byte has a larger value than the alpha byte.ColorU8
can implementAnyBitPattern
but doesn't.https://github.com/Pr0methean/OcHd-RustBuild/blob/main/main/src/image_tasks/png_output.rs#L312-L324