kevy_bytes/lib.rs
1//! `SmallBytes` — a 24-byte small-byte-string with inline-SSO optimization.
2//!
3//! Layout (**little-endian only**): a union of two 24-byte variants, distinguished
4//! by the byte at offset 23:
5//!
6//! - **Inline**: `[u8; 23]` data, then `u8` tag holding the inline length
7//! (0..=22). The whole string lives in the value, no allocation.
8//! - **Heap (64-bit)**: `NonNull<u8>` ptr (8) + `usize` len (8) + `usize`
9//! cap_and_tag (8). The high byte of `cap_and_tag` overlaps byte 23 of
10//! the union and is fixed at `0xFF` (> 22) as the heap discriminator. The
11//! low 56 bits hold the heap capacity (up to 72 PB).
12//! - **Heap (32-bit)**: `NonNull<u8>` ptr (4) + `u32` len (4) + `u32`
13//! cap (4) + 11-byte pad, then `u8` tag fixed at `0xFF`. Same 24-byte
14//! total, same discriminator byte at offset 23 — pointer / len fields
15//! are 32-bit-native so a `wasm32-unknown-unknown` build picks up the
16//! right size without shifting a `usize` past its bit width.
17//!
18//! The 64-bit layout is the one the kevy server runs on, and is locked
19//! against perf-affecting changes (cfg-gated 32-bit alternative lives
20//! alongside it without touching any 64-bit code path).
21//!
22//! This lets us store every byte string up to 22 bytes — covering the vast
23//! majority of Redis-style values — without any pointer-chase, while keeping
24//! `size_of::<SmallBytes>() == 24` (same as `Vec<u8>`). Used by `kevy-store`
25//! to make `Value::Str(SmallBytes)` fit alongside the boxed collection
26//! variants and keep `Entry` at 48 B.
27
28#![warn(missing_docs)]
29
30#[cfg(target_endian = "big")]
31compile_error!("kevy-bytes requires little-endian: heap-tag byte overlaps inline length byte");
32
33mod traits;
34
35use std::alloc::{Layout, alloc, dealloc, handle_alloc_error};
36use std::mem::{self, ManuallyDrop};
37use std::ptr::NonNull;
38use std::slice;
39
40pub(crate) const INLINE_CAP: usize = 23;
41pub(crate) const INLINE_LEN_MAX: u8 = (INLINE_CAP - 1) as u8;
42
43#[cfg(target_pointer_width = "64")]
44const TAG_HEAP_BIT: usize = 0xFFusize << 56;
45#[cfg(target_pointer_width = "64")]
46const CAP_MASK: usize = (1usize << 56) - 1;
47
48/// Heap-rep marker byte at offset 23. Used by the 32-bit `Heap::new` to
49/// set its dedicated `tag` field; the 64-bit path encodes the same byte
50/// implicitly via the high byte of `cap_and_tag`.
51#[cfg(target_pointer_width = "32")]
52const HEAP_TAG_BYTE: u8 = 0xFF;
53
54#[repr(C)]
55#[derive(Copy, Clone)]
56struct Inline {
57 data: [u8; INLINE_CAP],
58 /// 0..=22 = inline length. The heap rep sets this byte to 0xFF either via
59 /// the high byte of `Heap::cap_and_tag` (64-bit, little-endian overlap)
60 /// or as a dedicated `tag` field at offset 23 (32-bit).
61 tag: u8,
62}
63
64/// 64-bit Heap rep — `ptr|len|cap_and_tag` × usize. High byte of
65/// `cap_and_tag` shadows `Inline::tag` (LE) so the discriminator byte at
66/// offset 23 = `0xFF`. Locked layout: the kevy server runs here and the
67/// perf budget assumes this exact shape.
68#[cfg(target_pointer_width = "64")]
69#[repr(C)]
70#[derive(Copy, Clone)]
71pub(crate) struct Heap {
72 pub(crate) ptr: NonNull<u8>,
73 pub(crate) len: usize,
74 /// High byte = 0xFF (heap marker, shadows `Inline::tag`); low 56 bits =
75 /// capacity (from the source `Vec<u8>` or our own alloc; ≥ len).
76 pub(crate) cap_and_tag: usize,
77}
78
79/// 32-bit Heap rep — `ptr(4)|len(4)|cap(4)|pad(11)|tag(1)`. The dedicated
80/// `tag` byte at offset 23 (= `0xFF`) plays the role the 64-bit `cap_and_tag`
81/// high byte does, so the discriminator check at offset 23 stays identical
82/// across both layouts. Unlocks `wasm32-unknown-unknown` (Wave 3 #7) without
83/// touching the 64-bit hot path.
84#[cfg(target_pointer_width = "32")]
85#[repr(C)]
86#[derive(Copy, Clone)]
87pub(crate) struct Heap {
88 pub(crate) ptr: NonNull<u8>,
89 pub(crate) len: u32,
90 pub(crate) cap: u32,
91 pub(crate) _pad: [u8; 11],
92 pub(crate) tag: u8,
93}
94
95impl Heap {
96 /// Build a Heap rep tagging the discriminator byte to `0xFF`. cfg-gated
97 /// so each pointer-width hits its native fields without runtime cost.
98 #[cfg(target_pointer_width = "64")]
99 #[inline]
100 pub(crate) fn new(ptr: NonNull<u8>, len: usize, cap: usize) -> Self {
101 debug_assert!(cap <= CAP_MASK, "kevy-bytes: capacity exceeds 56-bit field");
102 Self {
103 ptr,
104 len,
105 cap_and_tag: TAG_HEAP_BIT | (cap & CAP_MASK),
106 }
107 }
108 #[cfg(target_pointer_width = "32")]
109 #[inline]
110 pub(crate) fn new(ptr: NonNull<u8>, len: usize, cap: usize) -> Self {
111 // On 32-bit, `Vec<u8>` is bounded by the 4 GiB address space, so
112 // any source `len`/`cap` already fits in `u32`. Debug-assert to
113 // catch unexpected callers.
114 debug_assert!(
115 len <= u32::MAX as usize && cap <= u32::MAX as usize,
116 "kevy-bytes: len/cap exceeds u32 on 32-bit platform"
117 );
118 Self {
119 ptr,
120 len: len as u32,
121 cap: cap as u32,
122 _pad: [0; 11],
123 tag: HEAP_TAG_BYTE,
124 }
125 }
126
127 /// Live capacity (always returned as `usize` regardless of underlying
128 /// field width).
129 #[cfg(target_pointer_width = "64")]
130 #[inline]
131 fn capacity(&self) -> usize {
132 self.cap_and_tag & CAP_MASK
133 }
134 #[cfg(target_pointer_width = "32")]
135 #[inline]
136 fn capacity(&self) -> usize {
137 self.cap as usize
138 }
139
140 /// Live length (always `usize`).
141 #[cfg(target_pointer_width = "64")]
142 #[inline]
143 fn length(&self) -> usize {
144 self.len
145 }
146 #[cfg(target_pointer_width = "32")]
147 #[inline]
148 fn length(&self) -> usize {
149 self.len as usize
150 }
151}
152
153/// A 24-byte owned byte string with inline small-string optimization.
154///
155/// Strings of up to 22 bytes live entirely inside the value (no allocation,
156/// no pointer chase); larger strings spill to a heap buffer. The
157/// discriminator is a single byte at offset 23 (the tag, which doubles as
158/// the inline length 0..=22 OR equals 0xFF when the heap variant is active).
159///
160/// See the crate root for layout details.
161#[repr(C)]
162pub union SmallBytes {
163 inline: Inline,
164 heap: Heap,
165}
166
167const _: () = {
168 assert!(mem::size_of::<SmallBytes>() == 24);
169 assert!(mem::align_of::<SmallBytes>() == mem::align_of::<usize>());
170};
171
172unsafe impl Send for SmallBytes {}
173unsafe impl Sync for SmallBytes {}
174
175impl SmallBytes {
176 /// Empty inline `SmallBytes` (zero allocation).
177 pub const fn new() -> Self {
178 Self {
179 inline: Inline {
180 data: [0; INLINE_CAP],
181 tag: 0,
182 },
183 }
184 }
185
186 /// Construct from a byte slice — inline if `bytes.len() <= 22`, else heap.
187 pub fn from_slice(bytes: &[u8]) -> Self {
188 if bytes.len() <= INLINE_LEN_MAX as usize {
189 let mut data = [0u8; INLINE_CAP];
190 // SAFETY: bytes.len() ≤ 22 ≤ data.len(); non-overlapping regions.
191 unsafe {
192 std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.as_mut_ptr(), bytes.len());
193 }
194 Self {
195 inline: Inline {
196 data,
197 tag: bytes.len() as u8,
198 },
199 }
200 } else {
201 Self::alloc_heap(bytes)
202 }
203 }
204
205 /// Take ownership of a `Vec<u8>` — inline if `vec.len() <= 22`, else **reuse
206 /// the vec's allocation** (no copy on the heap path).
207 pub fn from_vec(vec: Vec<u8>) -> Self {
208 if vec.len() <= INLINE_LEN_MAX as usize {
209 Self::from_slice(&vec)
210 } else {
211 let mut v = ManuallyDrop::new(vec);
212 // SAFETY: len > 22 ⇒ cap > 0 ⇒ Vec has an allocation, so the pointer
213 // is non-null. Vec guarantees a non-null pointer for any allocated
214 // Vec (and a dangling-but-non-null for empty, which we don't hit here).
215 let ptr = unsafe { NonNull::new_unchecked(v.as_mut_ptr()) };
216 let len = v.len();
217 let cap = v.capacity();
218 Self {
219 heap: Heap::new(ptr, len, cap),
220 }
221 }
222 }
223
224 #[inline]
225 fn alloc_heap(bytes: &[u8]) -> Self {
226 let len = bytes.len();
227 // `len > 22` (caller has already taken the heap branch) and `len` is
228 // a slice length ⇒ ≤ `isize::MAX` ⇒ well below the `usize::MAX -
229 // (align - 1)` bound `from_size_align_unchecked` needs. u8's align is 1.
230 // SAFETY: see above.
231 let layout = unsafe { Layout::from_size_align_unchecked(len, 1) };
232 // SAFETY: layout.size() > 0 (caller's heap branch guarantees len > 22).
233 let raw = unsafe { alloc(layout) };
234 let ptr = match NonNull::new(raw) {
235 Some(p) => p,
236 None => handle_alloc_error(layout),
237 };
238 // SAFETY: alloc returned a writable region of `len` bytes; source is a
239 // disjoint slice.
240 unsafe {
241 std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr.as_ptr(), len);
242 }
243 Self {
244 heap: Heap::new(ptr, len, len),
245 }
246 }
247
248 /// True when stored inline; the byte at index 23 is the deciding tag in
249 /// either rep, so the check is a single load + compare.
250 #[inline]
251 fn is_inline(&self) -> bool {
252 // SAFETY: byte 23 is always initialised — either as Inline::tag (0..=22)
253 // or as the high byte of Heap::cap_and_tag (= 0xFF). Reading it through
254 // the Inline view is valid in either case (the union is `repr(C)`).
255 unsafe { self.inline.tag <= INLINE_LEN_MAX }
256 }
257
258 /// Number of bytes stored.
259 #[inline]
260 pub fn len(&self) -> usize {
261 if self.is_inline() {
262 // SAFETY: just verified `inline.tag` ≤ 22.
263 unsafe { self.inline.tag as usize }
264 } else {
265 // SAFETY: tag > 22 ⇒ heap variant is active.
266 unsafe { self.heap.length() }
267 }
268 }
269
270 /// Whether `len() == 0`.
271 #[inline]
272 pub fn is_empty(&self) -> bool {
273 self.len() == 0
274 }
275
276 /// Bytes this value holds on the heap (0 when inline). Lets memory-accounting
277 /// callers (e.g. `maxmemory` enforcement) charge only the off-stack footprint
278 /// without re-deriving the inline-length threshold.
279 #[inline]
280 pub fn heap_bytes(&self) -> usize {
281 if self.is_inline() { 0 } else { self.len() }
282 }
283
284 /// Borrow the bytes (no allocation; same for inline and heap variants).
285 #[inline]
286 pub fn as_slice(&self) -> &[u8] {
287 if self.is_inline() {
288 // SAFETY: first `tag` bytes of `data` are valid (zero-init at construction).
289 unsafe {
290 slice::from_raw_parts(self.inline.data.as_ptr(), self.inline.tag as usize)
291 }
292 } else {
293 // SAFETY: heap variant active; ptr/len originate from a Vec or our own alloc.
294 unsafe { slice::from_raw_parts(self.heap.ptr.as_ptr(), self.heap.length()) }
295 }
296 }
297
298 /// Copy into a fresh `Vec<u8>` (clone semantics).
299 pub fn to_vec(&self) -> Vec<u8> {
300 self.as_slice().to_vec()
301 }
302
303 /// Consume self and return an owned `Vec<u8>`. The heap path reuses the
304 /// existing allocation; the inline path copies into a new vec.
305 pub fn into_vec(self) -> Vec<u8> {
306 if self.is_inline() {
307 self.as_slice().to_vec()
308 // self drops as inline — nothing to free.
309 } else {
310 // SAFETY: heap variant active.
311 let (ptr, len, cap) = unsafe {
312 (
313 self.heap.ptr.as_ptr(),
314 self.heap.length(),
315 self.heap.capacity(),
316 )
317 };
318 // Skip our Drop to avoid double-free; Vec::from_raw_parts now owns it.
319 let _do_not_drop = ManuallyDrop::new(self);
320 // SAFETY: ptr/len/cap originated from either a Vec<u8> (from_vec)
321 // or our own `alloc(Layout::array::<u8>(cap))` (alloc_heap, where
322 // cap == len) — both meet Vec::from_raw_parts' requirements.
323 unsafe { Vec::from_raw_parts(ptr, len, cap) }
324 }
325 }
326}
327
328impl Default for SmallBytes {
329 fn default() -> Self {
330 Self::new()
331 }
332}
333
334impl Drop for SmallBytes {
335 fn drop(&mut self) {
336 if self.is_inline() {
337 return;
338 }
339 // SAFETY: heap variant active; layout matches the one used at alloc
340 // time (either from Vec — Vec uses `Layout::array::<u8>(cap)` — or our
341 // own alloc_heap which used the same layout).
342 unsafe {
343 let cap = self.heap.capacity();
344 let layout = Layout::array::<u8>(cap).expect("kevy-bytes: drop layout");
345 dealloc(self.heap.ptr.as_ptr(), layout);
346 }
347 }
348}
349
350impl Clone for SmallBytes {
351 /// Specialised clone that bypasses `as_slice → from_slice → alloc_heap`'s
352 /// two layered length checks. Inline variant is a bitwise union copy (no
353 /// branch through the slice path); heap variant goes straight to a single
354 /// `alloc + memcpy` keyed on the already-known heap length.
355 #[inline]
356 fn clone(&self) -> Self {
357 if self.is_inline() {
358 // SAFETY: `Inline` is `repr(C)` + `Copy`; bitwise copy is sound
359 // when the source is currently in the inline variant (the tag
360 // byte ≤ 22 is part of the bit pattern we're copying, so the
361 // discriminator stays correct).
362 unsafe { Self { inline: self.inline } }
363 } else {
364 // SAFETY: tag > 22 ⇒ heap variant is active.
365 unsafe { self.clone_heap() }
366 }
367 }
368}
369
370impl SmallBytes {
371 /// Heap-fast-path clone. Caller must have established that `self` is in
372 /// the heap variant.
373 ///
374 /// # Safety
375 /// `self.heap` must be the active union variant (i.e. `is_inline()` is
376 /// false). `self.heap.ptr` must point to `self.heap.len` valid bytes.
377 #[inline]
378 unsafe fn clone_heap(&self) -> Self {
379 // SAFETY (covers the three `self.heap.*` reads): caller asserts the
380 // heap variant is active.
381 let (src_ptr, len) = unsafe { (self.heap.ptr.as_ptr(), self.heap.length()) };
382 // `len > 22 ⇒ len > 0`, and the high bits are guarded by `CAP_MASK`
383 // never letting cap exceed 2^56, well below `isize::MAX`, so the
384 // unchecked layout is sound. Allocator alignment for `u8` is 1.
385 let layout = unsafe { Layout::from_size_align_unchecked(len, 1) };
386 // SAFETY: layout.size() > 0.
387 let raw = unsafe { alloc(layout) };
388 let ptr = match NonNull::new(raw) {
389 Some(p) => p,
390 None => handle_alloc_error(layout),
391 };
392 // SAFETY: src has `len` valid bytes; dst is freshly-allocated for `len`
393 // bytes; regions are disjoint.
394 unsafe { std::ptr::copy_nonoverlapping(src_ptr, ptr.as_ptr(), len) };
395 Self {
396 heap: Heap::new(ptr, len, len),
397 }
398 }
399}
400
401// `Debug`, `PartialOrd`, `Ord`, `Hash`, `AsRef<[u8]>`, `Borrow<[u8]>`,
402// `KevyHash`, `From<&[u8]>`, `From<Vec<u8>>` live in `crate::traits` —
403// they only need the public `as_slice()` view. `PartialEq` / `Eq` stay
404// here because the same-variant fast paths reach into `self.inline` /
405// `self.heap` directly.
406
407impl PartialEq for SmallBytes {
408 /// Specialised over the slice form (`as_slice == as_slice`) by branching
409 /// on variant **once** and reading the relevant length / pointer pair
410 /// directly. Same-variant cases (inline/inline + heap/heap, which are the
411 /// only ones produced by a single allocator) skip a redundant `as_slice`
412 /// dispatch on each side; the mixed case falls back to the slice form.
413 #[inline]
414 fn eq(&self, other: &Self) -> bool {
415 // SAFETY: byte 23 (`inline.tag`) is always a valid load in either
416 // variant — it's either the inline-length 0..=22 or 0xFF as the
417 // heap-discriminator overlap (see crate doc).
418 let self_tag = unsafe { self.inline.tag };
419 let other_tag = unsafe { other.inline.tag };
420 let self_inline = self_tag <= INLINE_LEN_MAX;
421 let other_inline = other_tag <= INLINE_LEN_MAX;
422 match (self_inline, other_inline) {
423 (true, true) => {
424 let len = self_tag as usize;
425 if len != other_tag as usize {
426 return false;
427 }
428 // SAFETY: both in inline variant; first `len` bytes valid.
429 let a = unsafe {
430 slice::from_raw_parts(self.inline.data.as_ptr(), len)
431 };
432 let b = unsafe {
433 slice::from_raw_parts(other.inline.data.as_ptr(), len)
434 };
435 a == b
436 }
437 (false, false) => {
438 // SAFETY: both in heap variant.
439 let (a_len, b_len) =
440 unsafe { (self.heap.length(), other.heap.length()) };
441 if a_len != b_len {
442 return false;
443 }
444 // SAFETY: heap pointers + len are valid.
445 let a = unsafe {
446 slice::from_raw_parts(self.heap.ptr.as_ptr(), a_len)
447 };
448 let b = unsafe {
449 slice::from_raw_parts(other.heap.ptr.as_ptr(), b_len)
450 };
451 a == b
452 }
453 // Mixed inline/heap: this IS reachable in normal operation.
454 // It happens whenever HashMap (or any `==` consumer) compares
455 // an inline-length value (len ≤ 22) against a heap-length
456 // value (len > 22). Two SmallBytes of different lengths can
457 // *collide* on hashbrown's hash + quadratic probe, and the
458 // probe checks equality even though the lengths differ. The
459 // pre-fix `unreachable!()` here was a logic bug — it assumed
460 // the same-arm short-circuits cover all cases, but they only
461 // fire when both sides land in the same arm. Different-length
462 // collisions correctly fall through here. The right answer
463 // is just slice-form equality (which short-circuits on `len`
464 // internally), giving `false` whenever the lengths differ.
465 _ => self.as_slice() == other.as_slice(),
466 }
467 }
468}
469impl Eq for SmallBytes {}
470
471
472#[cfg(test)]
473mod tests;