Crate thin_boxed_slice

source ·
Expand description

ThinBoxedSlice stores the size of the slice before the content of the slice, so that size_of::<ThinBoxedSlice> is only the size of a pointer:

use core::mem::size_of;
use thin_boxed_slice::ThinBoxedSlice;
assert_eq!(size_of::<ThinBoxedSlice<u8>>(), size_of::<*mut u8>());

§Examples

use thin_boxed_slice::ThinBoxedSlice;
use core::ops::Deref;

let data = &[1, 2, 3];
let result = ThinBoxedSlice::<i32>::from(data);
assert_eq!(result.len(), 3);
assert_eq!(result.deref(), data);

ThinBoxedSlice is extremely useful to be the key of hash tables, because hash tables usually allocates more slots than elements to reduce hash collisions, and reduce the size of key with ThinBoxedSlice can reduce the memory consumption of extra slots allocated. Example:

use thin_boxed_slice::ThinBoxedSlice;
use std::collections::HashSet;
use std::ops::Deref;

let mut s: HashSet<ThinBoxedSlice<u8>> = HashSet::new();
s.insert(ThinBoxedSlice::from("123".as_bytes()));
s.insert(ThinBoxedSlice::from("456".as_bytes()));
assert_eq!(s.get("123".as_bytes()).unwrap().deref(), "123".as_bytes());

Structs§