-
-
Save thomcc/67854fada2e65ceef7d5cf4ee93d7a86 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 🚨 This is UB in current Rust! | |
fn new_vec_reusing_memory<T, U>(mut old: Vec<U>) -> Vec<T> { | |
if size_of::<T>() == 0 | |
|| size_of::<U>() == 0 | |
|| align_of::<T>() > align_of::<U>() | |
|| old.capacity() == 0 | |
{ | |
return vec![]; | |
} | |
old.clear(); | |
let p = old.as_mut_ptr(); | |
let cap_bytes = old.capacity() * size_of::<U>(); | |
let new_cap = cap_bytes / size_of::<T>(); | |
mem::forget(old); | |
Vec::from_raw_parts(p as *mut T, 0, new_cap) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment