[back]
Rust Custom Box Implementation
modified: 2015-03-22 04:22:15

    #![feature(unsafe_destructor)]
    #![allow(dead_code)]

    use std::rt::heap;
    use std::ptr;
    use std::mem;

    struct MyBox<T> {
        thing: *mut T,
    }

    impl<T> MyBox<T> {
        fn new(x: T) -> MyBox<T> {
            unsafe {
                let thing = heap::allocate(mem::size_of::<T>(), mem::align_of::<T>())
                    as *mut T;
                ptr::write(thing, x);
                MyBox { thing: thing }
            }
        }
    }

    #[unsafe_destructor]
    impl<T> Drop for MyBox<T> {
        fn drop(&mut self) {
            unsafe {
                ptr::read(self.thing as *const T); // run the destructor

                heap::deallocate(self.thing as *mut u8,
                    mem::size_of::<T>(), mem::align_of::<T>());
            }
        }
    }

    impl<T> Deref<T> for MyBox<T> {
        fn deref<'a>(&'a self) -> &'a T {
            unsafe { &*self.thing }
        }
    }

    impl<T> DerefMut<T> for MyBox<T> {
        fn deref_mut<'a>(&'a mut self) -> &'a mut T {
            unsafe { &mut *self.thing }
        }
    }

    // testing

    struct Foo {
        x: uint,
        y: uint,
    }

    impl Drop for Foo {
        fn drop(&mut self) {
            println!("dropped");
        }
    }

    fn main() {
        println!("sizes: unboxed {}, boxed {}",
            mem::size_of::<Foo>(), mem::size_of::<MyBox<Foo>>());

        {
            let b: MyBox<Foo> = MyBox::new(Foo { x: 3, y: 4 });
            println!("x = {}", b.x);
            println!("end of inner scope");
        }
        println!("end of outer scope");
    }