Skip to content

Instantly share code, notes, and snippets.

@ClarkeRemy
Last active November 21, 2023 08:23
Show Gist options
  • Save ClarkeRemy/f98d77726fd91e831ccc3c3309cfac47 to your computer and use it in GitHub Desktop.
Save ClarkeRemy/f98d77726fd91e831ccc3c3309cfac47 to your computer and use it in GitHub Desktop.
Basic Box
#![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