Guest User

Untitled

a guest
Nov 14th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. use core::mem;
  2. use std::ops::{Deref, DerefMut};
  3. use std::ptr::drop_in_place;
  4.  
  5. #[repr(transparent)]
  6. pub struct Box1<T: 'static> {
  7. ptr: &'static mut T,
  8. }
  9.  
  10. impl<T> Box1<T> {
  11. pub fn new(ptr: &'static mut T) -> Self {
  12. Self { ptr: ptr }
  13. }
  14.  
  15. #[inline]
  16. pub fn as_ptr(self) -> &'static mut T {
  17. let ref_ = self.ptr as *mut T;
  18. mem::forget(self);
  19. unsafe { &mut *ref_ }
  20. }
  21. }
  22.  
  23. impl<T: 'static> Deref for Box1<T> {
  24. type Target = T;
  25.  
  26. #[inline]
  27. fn deref(&self) -> &T {
  28. self.ptr
  29. }
  30. }
  31.  
  32. impl<T: 'static> DerefMut for Box1<T> {
  33. #[inline]
  34. fn deref_mut(&mut self) -> &mut T {
  35. self.ptr
  36. }
  37. }
  38.  
  39. impl<T> Drop for Box1<T> {
  40. fn drop(&mut self) {
  41. //Call destructor of T (if exists)
  42. let ptr = self.deref_mut();
  43. unsafe {
  44. drop_in_place(ptr);
  45. }
  46. }
  47. }
  48.  
  49. fn main() {
  50.  
  51. }
Add Comment
Please, Sign In to add comment