Guest User

Untitled

a guest
Jun 20th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. use std::ptr;
  2. #[derive(Debug, Default)]
  3. struct Foo {
  4. v: Vec<u32>,
  5. }
  6.  
  7.  
  8. fn zeroed<T>(item: &mut T) {
  9. let mut ptr = item as *mut _ as *mut u8;
  10.  
  11. let mut n = 0;
  12.  
  13. let untill = std::mem::size_of::<T>();
  14.  
  15. while n as usize + 8 <= untill {
  16. unsafe {
  17. ptr::write(ptr.offset(n + 0), 0);
  18. ptr::write(ptr.offset(n + 1), 0);
  19. ptr::write(ptr.offset(n + 2), 0);
  20. ptr::write(ptr.offset(n + 3), 0);
  21. ptr::write(ptr.offset(n + 4), 0);
  22. ptr::write(ptr.offset(n + 5), 0);
  23. ptr::write(ptr.offset(n + 6), 0);
  24. ptr::write(ptr.offset(n + 7), 0);
  25. }
  26.  
  27. n += 8;
  28. }
  29.  
  30. println!("Status after unrolled loop: n = {}, size_of::<T> = {}, bits = {}", n, untill, n * 8);
  31.  
  32. for offset in n..untill as isize {
  33. println!("fixup loop round {}", offset);
  34. unsafe {
  35. ptr::write(ptr.offset(n + offset), 0);
  36. }
  37. }
  38. }
  39. fn main() {
  40. let mut f = Foo {
  41. v: Vec::new(),
  42. };
  43.  
  44. zeroed(&mut f);
  45. println!("{:?}", f);
  46.  
  47. println!("{:?}", f.v);
  48.  
  49. for i in 0..100 {
  50. f.v.push(i);
  51. }
  52.  
  53. println!("{:?}", f.v);
  54.  
  55. }
Add Comment
Please, Sign In to add comment