#hash-table #slice #size #memory-size #key-hash #pointers #heap-memory

thin-boxed-slice

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

7 releases

0.2.5 Apr 29, 2024
0.2.4 Apr 29, 2024
0.1.1 Apr 29, 2024

#1474 in Rust patterns

MPL-2.0 license

8KB
116 lines

thin-boxed-slice

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.

I mainly use it as the key of hash tables, therefore not all traits of Box are implemented for ThinBoxedSlice. If you need some additional traits, you may create an issue or PR.

Similar projects

thin-vec

thin-slice

Note that thin-slice stores the fat pointer of the slice into a new heap memory if the slice length is large.


lib.rs:

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());

Dependencies

~260KB