Reference-counting garbage collection can be quite efficient

We could do this right now, with no change to the compiler

impl<T: ?Sized> Box<T> {
    fn try_reuse<N>(self, new: N) -> Result<Box<N>, Self> {
        self.try_reuse_with(|| new)
    }

    fn try_reuse_with<N, F>(self, new: F) -> Result<Box<N>, Self> 
    where F: FnOnce() -> N {
        use std::alloc::Layout;
       
        let layout = Layout::for_value(&*self);

        if layout == Layout::new::<N>() {
            unsafe {
                let ptr = Box::into_raw(self);
                ptr.drop_in_place();
                
                let ptr = ptr as *mut N;
                ptr.write(new());
                
                Ok(Box::from_raw(ptr))
            }
        } else {
            Err(self)
        }
    }
}
4 Likes