Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. use std::{alloc, mem, ptr};
  2.  
  3. const ALIGNMENT: usize = 4; //TODO
  4.  
  5. /// A typesafe helper that stores the allocated pointer without the data initialized.
  6. pub struct BoxAllocation<T>(*mut T);
  7.  
  8. impl<T> BoxAllocation<T> {
  9. /// Consumes self and writes the given value into the allocation.
  10. pub fn init(mut self, value: T) -> Box<T> {
  11. let ptr = mem::replace(&mut self.0, ptr::null_mut());
  12. unsafe {
  13. ptr::write(ptr, value);
  14. Box::from_raw(ptr)
  15. }
  16. }
  17. }
  18.  
  19. impl<T> Drop for BoxAllocation<T> {
  20. fn drop(&mut self) {
  21. if !self.0.is_null() {
  22. let layout = alloc::Layout::from_size_align(mem::size_of::<T>(), ALIGNMENT).unwrap();
  23. unsafe {
  24. alloc::dealloc(self.0 as *mut u8, layout);
  25. }
  26. }
  27. }
  28. }
  29.  
  30.  
  31. /// Helper trait for a `Box` type that allocates up-front.
  32. pub trait BoxHelper<T> {
  33. /// Allocates the storage without providing any data.
  34. fn alloc() -> BoxAllocation<T>;
  35. }
  36.  
  37. impl<T> BoxHelper<T> for Box<T> {
  38. fn alloc() -> BoxAllocation<T> {
  39. let layout = alloc::Layout::from_size_align(mem::size_of::<T>(), ALIGNMENT).unwrap();
  40. BoxAllocation(unsafe {
  41. alloc::alloc(layout) as *mut T
  42. })
  43. }
  44. }
  45.  
  46.  
  47. enum Foo {
  48. Small(i8),
  49. Big {
  50. x: [f32; 100],
  51. y: [i32; 100],
  52. },
  53. }
  54.  
  55. #[inline(never)]
  56. fn foo() -> Box<Foo> {
  57. Box::new(Foo::Small(4))
  58. // Box::alloc().init(Foo::Small(4))
  59. }
  60.  
  61. fn main() {
  62. let z = foo();
  63. println!("{:?}", &*z as *const _);
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement