I have a function that reads a Vec<u8> from disk that I want to interpret as the ext2 super block (which is a packed struct).
So I used:
unsafe {&*(raw_super.as_ptr() as *const Super block)}
The problem is when the function returns the Vec is dropped, so the super block is only 0s
I want a way to transform the Vec into a super block and own the data in super block, with if possible a small cost abstraction
As others have noted in the comments before, you have to assert a couple of preconditions first:
u8andSuperBlockis the same (butu8and a#[repr(packed)]struct always fulfill thatpackedis implicitlypacked(1))Vec<u8>(it'slen()) is the same as the size of aSuperBlockext2So you can convert your
Vec<u8>to aBox<SuperBlock>like this:Playground
Technically, this does not drop the
Vec, instead it reuses the same allocation for the returnedBox<SuperBlock>