What happens if I call Vec :: from_raw_parts with less capacity than the actual pointer?

I have a vector u8 that I want to interpret as a vector u32 . Bytes are assumed to be in the correct order. I do not want to allocate new memory and copy bytes after casting. I got the following:

 use std::mem; fn reinterpret(mut v: Vec<u8>) -> Option<Vec<u32>> { let v_len = v.len(); v.shrink_to_fit(); if v_len % 4 != 0 { None } else { let v_cap = v.capacity(); let v_ptr = v.as_mut_ptr(); println!("{:?}|{:?}|{:?}", v_len, v_cap, v_ptr); let v_reinterpret = unsafe { Vec::from_raw_parts(v_ptr as *mut u32, v_len / 4, v_cap / 4) }; println!("{:?}|{:?}|{:?}", v_reinterpret.len(), v_reinterpret.capacity(), v_reinterpret.as_ptr()); println!("{:?}", v_reinterpret); println!("{:?}", v); // v is still alive, but is same as rebuilt mem::forget(v); Some(v_reinterpret) } } fn main() { let mut v: Vec<u8> = vec![1, 1, 1, 1, 1, 1, 1, 1]; let test = reinterpret(v); println!("{:?}", test); } 

However, there is an obvious problem. From the shrink_to_fit documentation :

It will fall as close to the length as possible, but the distributor can still tell the vector that there is room for a few more elements.

Does this mean that my ability still cannot be a multiple of u32 after calling shrink_to_fit ? If in from_raw_parts I set the capacity v_len/4 with v.capacity() not an exact multiple of 4, I will skip these 1-3 bytes or return to the memory pool due to mem::forget on v

Is there any other problem I'm looking at here?

I think moving v to reinterpret ensures that it is not accessible from this point, so that there is only one owner from the mem::forget(v) call and beyond.

+6
source share

All Articles