#buffer #zero-copy #io #byte-buffer

smallbytes

SmallBytes = SmallVec + impl BufMut (来自 bytes 包)

1个不稳定版本

0.1.0 2024年6月13日

#945 in 数据结构

MIT 许可证

9KB
152

Smallbytes

crates.io docs.rs

SmallBytes = SmallVec + impl BufMut (来自 bytes 包)

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"[..]);

SmallBytes 对象的大小至少为24字节(指针、长度、容量),类似于 Vec。这意味着您总是可以在堆栈上免费存储16字节。

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)

依赖项

~250KB