Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::ptr;
- #[derive(Debug, Default)]
- struct Foo {
- v: Vec<u32>,
- }
- fn zeroed<T>(item: &mut T) {
- let mut ptr = item as *mut _ as *mut u8;
- let mut n = 0;
- let untill = std::mem::size_of::<T>();
- while n as usize + 8 <= untill {
- unsafe {
- ptr::write(ptr.offset(n + 0), 0);
- ptr::write(ptr.offset(n + 1), 0);
- ptr::write(ptr.offset(n + 2), 0);
- ptr::write(ptr.offset(n + 3), 0);
- ptr::write(ptr.offset(n + 4), 0);
- ptr::write(ptr.offset(n + 5), 0);
- ptr::write(ptr.offset(n + 6), 0);
- ptr::write(ptr.offset(n + 7), 0);
- }
- n += 8;
- }
- println!("Status after unrolled loop: n = {}, size_of::<T> = {}, bits = {}", n, untill, n * 8);
- for offset in n..untill as isize {
- println!("fixup loop round {}", offset);
- unsafe {
- ptr::write(ptr.offset(n + offset), 0);
- }
- }
- }
- fn main() {
- let mut f = Foo {
- v: Vec::new(),
- };
- zeroed(&mut f);
- println!("{:?}", f);
- println!("{:?}", f.v);
- for i in 0..100 {
- f.v.push(i);
- }
- println!("{:?}", f.v);
- }
Add Comment
Please, Sign In to add comment