1 个稳定版本
使用旧的 Rust 2015
1.0.0 | 2017年1月29日 |
---|
#5 在 #boxing
8KB
199 行
maybe_box
maybe_box
是一个小的 Rust 库,用于在指针大小的内存块中存储任意数据,仅在必要时分配内存。
示例
// 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");
},
};
lib.rs
:
将任意数据存储在 usize
的大小中,仅在必要时进行封装。