Create a new vector that re-uses the same allocation as an old one. The element types must have the same size and alignment.
(mut v: Vec<T1>)
| 23 | /// Create a new vector that re-uses the same allocation as an old one. |
| 24 | /// The element types must have the same size and alignment. |
| 25 | pub fn repurpose_allocation<T1, T2>(mut v: Vec<T1>) -> Vec<T2> { |
| 26 | assert_eq!(size_of::<T1>(), size_of::<T2>(), "same size"); |
| 27 | assert_eq!(align_of::<T1>(), align_of::<T2>(), "same alignment"); |
| 28 | |
| 29 | v.clear(); |
| 30 | let cap = v.capacity(); |
| 31 | let p = v.as_mut_ptr().cast(); |
| 32 | std::mem::forget(v); |
| 33 | // This is safe because `T1` and `T2` have the same size and alignment, |
| 34 | // `p`'s allocation is no longer owned by `v` (since that has been forgotten), |
| 35 | // and `p` was previously allocated with capacity `cap`. |
| 36 | unsafe { Vec::from_raw_parts(p, 0, cap) } |
| 37 | } |
| 38 | |
| 39 | /// A trait for objects that behave like vectors. |
| 40 | pub trait Vector<T> { |
no test coverage detected