Lokathor/bytemuck

TransparentWrapper and alloc

TheEdward162 opened this issue · 4 comments

Is it possible to have something like cast_vec for TransparentWrapper types?

#[repr(transparent)]
#[derive(TransparentWrapper)]
struct Bar(Foo);

let a: Vec<Foo> = vec![Foo::new()];
let b: Vec<Bar> = Bar::wrap_vec(a);
let c: Vec<Foo> = Bar::peel_vec(b);

I'm not sure if this is sound but I cannot see any reason why not. I can imagine this being implemented either on the TransparentWrapper trait itself using feature gates, or using an extension trait that appears inside the allocation module.

Uh, yeah this should be fine. You can't transmute the vec directly but you can turn it into raw parts, cast the pointer, and rebuild the vec with a new element type. Basically how the existing cast_vec stuff works but you'd need even less runtime checking with the TransparentWrapper bound.

Can I open this as a PR, would you be fine with adding it to the crate? If so, should I go the route of adding it directly onto the TransparentWrapper trait or making an extension trait and doing impl<T: TransparentWrapper> TransparentWrapperAlloc for T {} somewhere inside allocation.rs I suppose?

A PR would be good, but I can't review it properly or write it myself until about 8hrs from now or so at the soonest.

And I think that an extension trait with a blanket impl is probably fine. Usually I'd just write a stand alone function for something like this, but an extension trait works too I suppose?

That's fine, I don't need it immediatelly 😅.

I would like it to behave the same as methods already on TransparentWrapper trait so that it is only a matter of enabling the feature.