Last active
November 21, 2023 08:23
-
-
Save ClarkeRemy/f98d77726fd91e831ccc3c3309cfac47 to your computer and use it in GitHub Desktop.
Basic Box
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![no_implicit_prelude] | |
pub(crate) extern crate alloc; // with heap | |
pub(crate) extern crate core; // fundamental | |
pub(crate) extern crate std; // OS | |
fn main() { | |
let _x = MyBox::new(alloc::vec![4]); | |
} | |
pub struct MyBox<T> { | |
ptr: *mut T, | |
phantom : core::marker::PhantomData<T> | |
} | |
impl<T> MyBox<T> { | |
pub fn new(val: T) -> Self { | |
unsafe { | |
let ptr = alloc::alloc::alloc(alloc::alloc::Layout::new::<T>()) as *mut T; | |
core::ptr::write(ptr, val); | |
MyBox { | |
ptr, | |
phantom : core::marker::PhantomData | |
} | |
} | |
} | |
pub fn unbox(self) -> T { | |
unsafe { | |
let out = self.ptr.read(); | |
alloc::alloc::dealloc(self.ptr as *mut u8, alloc::alloc::Layout::new::<T>()); | |
core::mem::forget(self); | |
out | |
} | |
} | |
} | |
// {} | |
impl<T> core::ops::Drop for MyBox<T> { | |
fn drop(&mut self) { | |
unsafe { | |
core::ptr::drop_in_place(self.ptr); | |
alloc::alloc::dealloc(self.ptr as *mut u8, alloc::alloc::Layout::new::<T>()); | |
} | |
} | |
} | |
impl<T> core::ops::Deref for MyBox<T> { | |
type Target = T; | |
fn deref(&self) -> &Self::Target { | |
unsafe{&*self.ptr} | |
} | |
} | |
impl<T> core::ops::DerefMut for MyBox<T> { | |
fn deref_mut(&mut self) -> &mut Self::Target { | |
unsafe{&mut *self.ptr} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment