maybe_box 1.0.0

Store arbitrary data in the size of a pointer, only boxing if necessary
Documentation
  • Coverage
  • 88.89%
    8 out of 9 items documented0 out of 5 items with examples
  • Size
  • Source code size: 8.87 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.95 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • canndrew/maybe_box
    5 1 2
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • canndrew

maybe_box

maybe_box is a small Rust library for storing arbitrary data in a pointer-sized piece of memory, only allocating if necessary.

Example

// Wrap a bool into a MaybeBox.
// Because a bool is small enough to fit into the size of a pointer, this
// will not do any allocation.
let mb = MaybeBox::new(true);

// Extract the data back out again.
let my_bool = mb.into_inner();
assert_eq!(my_bool, true);

// Wrap a String into a MaybeBox
// Because a String is too big to fit into the size of a pointer, this
// *will* do allocation.
let mb = MaybeBox::new(String::from("hello"));

// We can unpack the MaybeBox to see whether it was boxed or not.
match mb.unpack() {
    maybe_box::Unpacked::Inline(_) => panic!("String wasn't boxed?!"),
    maybe_box::Unpacked::Boxed(b) => {
        // Unbox our string...
        let my_string = *b;

        // ... and get the String that we boxed.
        assert_eq!(&*my_string, "hello");
    },
};