Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Casts and conversions for owned, boxed slices #238

Open
Pr0methean opened this issue May 5, 2024 · 5 comments
Open

Casts and conversions for owned, boxed slices #238

Pr0methean opened this issue May 5, 2024 · 5 comments

Comments

@Pr0methean
Copy link

Pr0methean commented May 5, 2024

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

@zachs18
Copy link
Contributor

zachs18 commented May 5, 2024

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

@Pr0methean
Copy link
Author

Pr0methean commented May 5, 2024

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

@Pr0methean
Copy link
Author

@Lokathor
Copy link
Owner

Lokathor commented May 6, 2024

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
Copy link
Author

Pr0methean commented May 6, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants