Skip to content

Instantly share code, notes, and snippets.

@thomcc

thomcc/reuse.rs Secret

Last active Jun 11, 2020
Embed
What would you like to do?
// 🚨 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
You can’t perform that action at this time.