Skip to content

Instantly share code, notes, and snippets.

@rthomas
Created July 7, 2019 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rthomas/2fbf2b605839eb33ae9bec6a20dd4dfd to your computer and use it in GitHub Desktop.
Save rthomas/2fbf2b605839eb33ae9bec6a20dd4dfd to your computer and use it in GitHub Desktop.
MyBox Impl
use std::alloc::{GlobalAlloc, Layout, System};
use std::ops::{Deref, Drop};
use std::marker::PhantomData;
use std::{mem, ptr};
#[derive(Debug)]
struct MyBox<T> {
ptr: *mut u8,
size: usize,
align: usize,
phantom: PhantomData<T>,
}
impl<T> MyBox<T> {
pub fn new(p: T) -> MyBox<T> {
unsafe {
let layout = Layout::for_value(&p);
let ptr = System.alloc(layout);
ptr::copy_nonoverlapping(mem::transmute::<&T, *const u8>(&p), ptr, mem::size_of_val(&p));
MyBox {
ptr: ptr,
size: layout.size(),
align: layout.align(),
phantom: PhantomData,
}
}
}
}
impl<T> Drop for MyBox<T> {
fn drop(&mut self) {
unsafe {
System.dealloc(self.ptr, Layout::from_size_align_unchecked(self.size, self.align));
}
}
}
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe {
mem::transmute(self.ptr)
}
}
}
fn main() {
let b = MyBox::new(1234);
println!("Box: {:?}", b);
println!("Val: {:?}", *b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment