Crates.io | smallbytes |
lib.rs | smallbytes |
version | 0.1.0 |
source | src |
created_at | 2024-06-13 14:48:36.156542 |
updated_at | 2024-06-13 14:48:36.156542 |
description | SmallBytes = SmallVec + impl BufMut (from the bytes crate) |
homepage | |
repository | |
max_upload_size | |
id | 1270721 |
size | 9,605 |
SmallBytes = SmallVec + impl BufMut (from the bytes crate)
use smallbytes::SmallBytes;
use bytes::BufMut;
// initialize a buffer with inline capacity of 6 bytes
let mut buf = SmallBytes::<6>::new();
// the first word fits inline (stack)
buf.put(&b"hello"[..]);
// the rest does not, so the contents are moved to the heap
buf.put(&b" world"[..]);
buf.put_u16(1234);
assert_eq!(buf.as_ref(), &b"hello world\x04\xD2"[..]);
The size of a SmallBytes
object is at least 24 bytes (pointer, length, capacity) similar to a Vec
. This means you can always store 16 bytes on the stack for free.
use std::mem::size_of;
use smallbytes::SmallBytes;
assert_eq!(24, size_of::<SmallBytes<0>>()); // zero bytes on the stack, don't do this
assert_eq!(24, size_of::<SmallBytes<8>>()); // 8 bytes on the stack
assert_eq!(24, size_of::<SmallBytes<16>>()); // 16 bytes on the stack (ideal minimum)
assert_eq!(32, size_of::<SmallBytes<24>>()); // 24 bytes on the stack (stack size increases)