Created
July 7, 2019 03:53
-
-
Save rthomas/2fbf2b605839eb33ae9bec6a20dd4dfd to your computer and use it in GitHub Desktop.
MyBox Impl
This file contains 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
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