Repository navigation
Replies: 1 comment 1 reply
|
afaik there's no Box<[u8]> -> Box conversion in 0.8; the transmute macros only do values and refs. The catch for any safe API is the Box has to be freed with the layout it was allocated with, so it only works for align-1 types with no trailing padding. Yours qualifies, so a small unsafe block does it: fn into_boxed(bytes: Box<[u8]>) -> Result<Box<MyDst>, Box<[u8]>> {
let elems = match MyDst::try_ref_from_bytes(&bytes) {
Ok(r) => r.rest.len(),
Err(_) => return Err(bytes),
};
let raw = Box::into_raw(bytes);
let p = core::ptr::slice_from_raw_parts_mut(raw as *mut u8, elems) as *mut MyDst;
// SAFETY: validated above; MyDst is align 1, no trailing padding,
// so the layout matches the original Box<[u8]>.
Ok(unsafe { Box::from_raw(p) })
}Ran it under miri including the drop and it's clean. No need for ouroboros. If the type ever gets align > 1, copy into a new_box_zeroed_with_elems allocation instead. |
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I know that I can do
MyDST::try_ref_from_bytes(&box), but this gives a&MySlice. I'd like something that lets me actually get an owned version of this as a Box, is it possible?I'd really like to avoid having to reach for self-referential types via something like ouroboros.
I figured maybe I could
let v: Box<MyDST> = try_transmute!(box).unwrap(), but that didn't work.All reactions