Skip to main content

Crate my_box

Crate my_box 

Source
Expand description

§MyBox

A small, practical reimplementation of Box<T> in safe-Rust style.

This crate does one thing: it moves a value onto the heap, hands you a pointer-sized handle, and cleans up when you’re done. Nothing fancy — just enough to be useful in real code and to show how the standard Box<T> works under the hood.

use my_box::MyBox;

let num = MyBox::new(42);
assert_eq!(*num, 42);

let player = MyBox::new(String::from("Ryu"));
println!("{}", *player);

§Why does this exist?

Most Rust code never needs this — std::boxed::Box already does all of this and more, with optimizations the compiler can reason about. This crate is here because sometimes you want to see the full picture: alloc, write, drop_in_place, dealloc, and the trait glue that makes the * operator work the way you expect.

If you’re writing production code, use Box<T>. If you’re learning, or you need a try_new that doesn’t panic on OOM, this might be useful.

§Examples

§Recursive type via Box

use my_box::MyBox;

#[derive(Debug, PartialEq)]
enum List<T> {
    Cons(T, Box<List<T>>),
    Nil,
}

let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
println!("{:?}", list);

§What’s included

  • Normal heap allocationMyBox::new and MyBox::try_new
  • ZST support — won’t crash on () or PhantomData
  • Recursive typesBox<List<T>> works because the indirection is a known size
  • Trait objectsBox<dyn Trait> is just a fat pointer, works fine
  • Thread safetySend/Sync forwarded to T
  • Full accessDeref, DerefMut, AsRef, AsMut, Borrow, BorrowMut
  • Standard traitsClone, PartialEq, PartialOrd, Ord, Hash, Debug, Display, Default, From
  • Raw pointer interopinto_raw / from_raw for when you need to cross an unsafe boundary

Structs§

AllocError
MyBox