Skip to main content

kevy_bytes/
lib.rs

1//! `SmallBytes` — a 24-byte small-byte-string with inline-SSO optimization.
2//!
3//! ```
4//! use kevy_bytes::SmallBytes;
5//!
6//! // Up to 22 bytes live in the value itself — no allocation, and the
7//! // whole string fits in one 24-byte slot.
8//! let short = SmallBytes::from_slice(b"user:1");
9//! assert_eq!(short.as_slice(), b"user:1");
10//! assert_eq!(short.heap_bytes(), 0);
11//!
12//! // Past the inline capacity it spills to the heap, and says so.
13//! let long = SmallBytes::from_slice(&[b'x'; 64]);
14//! assert_eq!(long.len(), 64);
15//! assert!(long.heap_bytes() >= 64);
16//! ```
17//!
18//! Layout (**little-endian only**): a union of two 24-byte variants, distinguished
19//! by the byte at offset 23:
20//!
21//! - **Inline**: `[u8; 23]` data, then `u8` tag holding the inline length
22//!   (0..=22). The whole string lives in the value, no allocation.
23//! - **Heap (64-bit)**: `NonNull<u8>` ptr (8) + `usize` len (8) + `usize`
24//!   cap_and_tag (8). The high byte of `cap_and_tag` overlaps byte 23 of
25//!   the union and is fixed at `0xFF` (> 22) as the heap discriminator. The
26//!   low 56 bits hold the heap capacity (up to 72 PB).
27//! - **Heap (32-bit)**: `NonNull<u8>` ptr (4) + `u32` len (4) + `u32`
28//!   cap (4) + 11-byte pad, then `u8` tag fixed at `0xFF`. Same 24-byte
29//!   total, same discriminator byte at offset 23 — pointer / len fields
30//!   are 32-bit-native so a `wasm32-unknown-unknown` build picks up the
31//!   right size without shifting a `usize` past its bit width.
32//!
33//! The 64-bit layout is the one the kevy server runs on, and is locked
34//! against perf-affecting changes (cfg-gated 32-bit alternative lives
35//! alongside it without touching any 64-bit code path).
36//!
37//! This lets us store every byte string up to 22 bytes — covering the vast
38//! majority of Redis-style values — without any pointer-chase, while keeping
39//! `size_of::<SmallBytes>() == 24` (same as `Vec<u8>`). Used by `kevy-store`
40//! to make `Value::Str(SmallBytes)` fit alongside the boxed collection
41//! variants and keep `Entry` at 48 B.
42
43#![warn(missing_docs)]
44#![cfg_attr(not(feature = "std"), no_std)]
45
46extern crate alloc;
47
48#[cfg(target_endian = "big")]
49compile_error!("kevy-bytes requires little-endian: heap-tag byte overlaps inline length byte");
50
51mod eq;
52mod find_crlf;
53mod traits;
54
55mod heap;
56pub(crate) use heap::{Heap, INLINE_CAP, INLINE_LEN_MAX, Inline};
57
58pub use find_crlf::find_crlf;
59
60use alloc::alloc::{Layout, alloc, dealloc, handle_alloc_error};
61use alloc::vec::Vec;
62use core::mem::{self, ManuallyDrop};
63use core::ptr::NonNull;
64use core::slice;
65
66/// A 24-byte owned byte string with inline small-string optimization.
67///
68/// Strings of up to 22 bytes live entirely inside the value (no allocation,
69/// no pointer chase); larger strings spill to a heap buffer. The
70/// discriminator is a single byte at offset 23 (the tag, which doubles as
71/// the inline length 0..=22 OR equals 0xFF when the heap variant is active).
72///
73/// See the crate root for layout details.
74#[repr(C)]
75/// # Examples
76///
77/// Short values live inline; longer ones move to the heap. The API does not
78/// change, but `heap_bytes` reports which happened, which is what the
79/// keyspace's memory accounting reads.
80///
81/// ```
82/// use kevy_bytes::SmallBytes;
83/// let short = SmallBytes::from_slice(b"hello");
84/// assert_eq!(short.as_slice(), b"hello");
85/// assert_eq!(short.len(), 5);
86/// assert_eq!(short.heap_bytes(), 0, "a short value allocates nothing");
87///
88/// let long = SmallBytes::from_slice(&[b'x'; 100]);
89/// assert_eq!(long.len(), 100);
90/// assert!(long.heap_bytes() >= 100, "a long value is on the heap");
91/// ```
92///
93/// ```
94/// use kevy_bytes::SmallBytes;
95/// assert!(SmallBytes::from_slice(b"").is_empty());
96/// ```
97pub union SmallBytes {
98    // pub(crate) so `eq.rs` can branch on the variant directly; the union
99    // itself stays private to this crate's own modules.
100    pub(crate) inline: Inline,
101    pub(crate) heap: Heap,
102}
103
104const _: () = {
105    assert!(mem::size_of::<SmallBytes>() == 24);
106    assert!(mem::align_of::<SmallBytes>() == mem::align_of::<usize>());
107};
108
109unsafe impl Send for SmallBytes {}
110unsafe impl Sync for SmallBytes {}
111
112impl SmallBytes {
113    /// Empty inline `SmallBytes` (zero allocation).
114    ///
115    /// # Examples
116    ///
117    /// `const`, so it can seed a static or an array without a run-time
118    /// initialiser:
119    ///
120    /// ```
121    /// use kevy_bytes::SmallBytes;
122    /// static EMPTY: SmallBytes = SmallBytes::new();
123    /// assert!(EMPTY.is_empty());
124    /// assert_eq!(EMPTY.heap_bytes(), 0);
125    /// ```
126    pub const fn new() -> Self {
127        Self { inline: Inline { data: [0; INLINE_CAP], tag: 0 } }
128    }
129
130    /// Construct from a byte slice — inline if `bytes.len() <= 22`, else heap.
131    ///
132    /// # Examples
133    ///
134    /// Twenty-two is the boundary, and it is exact:
135    ///
136    /// ```
137    /// use kevy_bytes::SmallBytes;
138    /// assert_eq!(SmallBytes::from_slice(&[b'x'; 22]).heap_bytes(), 0);
139    /// assert_eq!(SmallBytes::from_slice(&[b'x'; 23]).heap_bytes(), 23);
140    /// ```
141    pub fn from_slice(bytes: &[u8]) -> Self {
142        if bytes.len() <= INLINE_LEN_MAX as usize {
143            let mut data = [0u8; INLINE_CAP];
144            // SAFETY: bytes.len() ≤ 22 ≤ data.len(); non-overlapping regions.
145            unsafe {
146                core::ptr::copy_nonoverlapping(bytes.as_ptr(), data.as_mut_ptr(), bytes.len());
147            }
148            Self { inline: Inline { data, tag: bytes.len() as u8 } }
149        } else {
150            Self::alloc_heap(bytes)
151        }
152    }
153
154    /// Take ownership of a `Vec<u8>` — inline if `vec.len() <= 22`, else **reuse
155    /// the vec's allocation** (no copy on the heap path).
156    ///
157    /// # Examples
158    ///
159    /// The heap path keeps the vec's own buffer, so a value that arrived as
160    /// a `Vec` is stored without a second copy:
161    ///
162    /// ```
163    /// use kevy_bytes::SmallBytes;
164    /// let v = vec![b'z'; 64];
165    /// let addr = v.as_ptr();
166    /// let b = SmallBytes::from_vec(v);
167    /// assert_eq!(b.as_slice().as_ptr(), addr, "same allocation, not a copy");
168    /// ```
169    ///
170    /// A short vec goes inline instead, and its allocation is released:
171    ///
172    /// ```
173    /// use kevy_bytes::SmallBytes;
174    /// assert_eq!(SmallBytes::from_vec(vec![b'a'; 4]).heap_bytes(), 0);
175    /// ```
176    pub fn from_vec(vec: Vec<u8>) -> Self {
177        if vec.len() <= INLINE_LEN_MAX as usize {
178            Self::from_slice(&vec)
179        } else {
180            let mut v = ManuallyDrop::new(vec);
181            // SAFETY: len > 22 ⇒ cap > 0 ⇒ Vec has an allocation, so the pointer
182            // is non-null. Vec guarantees a non-null pointer for any allocated
183            // Vec (and a dangling-but-non-null for empty, which we don't hit here).
184            let ptr = unsafe { NonNull::new_unchecked(v.as_mut_ptr()) };
185            let len = v.len();
186            let cap = v.capacity();
187            Self { heap: Heap::new(ptr, len, cap) }
188        }
189    }
190
191    #[inline]
192    fn alloc_heap(bytes: &[u8]) -> Self {
193        let len = bytes.len();
194        // `len > 22` (caller has already taken the heap branch) and `len` is
195        // a slice length ⇒ ≤ `isize::MAX` ⇒ well below the `usize::MAX -
196        // (align - 1)` bound `from_size_align_unchecked` needs. u8's align is 1.
197        // SAFETY: see above.
198        let layout = unsafe { Layout::from_size_align_unchecked(len, 1) };
199        // SAFETY: layout.size() > 0 (caller's heap branch guarantees len > 22).
200        let raw = unsafe { alloc(layout) };
201        let Some(ptr) = NonNull::new(raw) else { handle_alloc_error(layout) };
202        // SAFETY: alloc returned a writable region of `len` bytes; source is a
203        // disjoint slice.
204        unsafe {
205            core::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr.as_ptr(), len);
206        }
207        Self { heap: Heap::new(ptr, len, len) }
208    }
209
210    /// True when stored inline; the byte at index 23 is the deciding tag in
211    /// either rep, so the check is a single load + compare.
212    #[inline]
213    fn is_inline(&self) -> bool {
214        // SAFETY: byte 23 is always initialised — either as Inline::tag (0..=22)
215        // or as the high byte of Heap::cap_and_tag (= 0xFF). Reading it through
216        // the Inline view is valid in either case (the union is `repr(C)`).
217        unsafe { self.inline.tag <= INLINE_LEN_MAX }
218    }
219
220    /// Number of bytes stored.
221    ///
222    /// # Examples
223    ///
224    /// The same answer either side of the inline boundary — which is the
225    /// point of the type: where the bytes live is not the caller's problem.
226    ///
227    /// ```
228    /// use kevy_bytes::SmallBytes;
229    /// assert_eq!(SmallBytes::from_slice(&[0u8; 22]).len(), 22);
230    /// assert_eq!(SmallBytes::from_slice(&[0u8; 23]).len(), 23);
231    /// ```
232    #[inline]
233    pub fn len(&self) -> usize {
234        if self.is_inline() {
235            // SAFETY: just verified `inline.tag` ≤ 22.
236            unsafe { self.inline.tag as usize }
237        } else {
238            // SAFETY: tag > 22 ⇒ heap variant is active.
239            unsafe { self.heap.length() }
240        }
241    }
242
243    /// Whether `len() == 0`.
244    ///
245    /// # Examples
246    ///
247    /// ```
248    /// use kevy_bytes::SmallBytes;
249    /// assert!(SmallBytes::from_slice(b"").is_empty());
250    /// assert!(!SmallBytes::from_slice(b"\0").is_empty(), "a NUL byte is a byte");
251    /// ```
252    #[inline]
253    pub fn is_empty(&self) -> bool {
254        self.len() == 0
255    }
256
257    /// Bytes this value holds on the heap (0 when inline). Lets memory-accounting
258    /// callers (e.g. `maxmemory` enforcement) charge only the off-stack footprint
259    /// without re-deriving the inline-length threshold.
260    ///
261    /// # Examples
262    ///
263    /// This is what `maxmemory` charges, so an inline value must cost zero
264    /// — it is already inside the entry the keyspace has counted:
265    ///
266    /// ```
267    /// use kevy_bytes::SmallBytes;
268    /// assert_eq!(SmallBytes::from_slice(b"user:1").heap_bytes(), 0);
269    /// assert_eq!(SmallBytes::from_slice(&[b'x'; 1000]).heap_bytes(), 1000);
270    /// ```
271    #[inline]
272    pub fn heap_bytes(&self) -> usize {
273        if self.is_inline() { 0 } else { self.len() }
274    }
275
276    /// Borrow the bytes (no allocation; same for inline and heap variants).
277    ///
278    /// # Examples
279    ///
280    /// ```
281    /// use kevy_bytes::SmallBytes;
282    /// let b = SmallBytes::from_slice(b"GET");
283    /// assert_eq!(b.as_slice(), b"GET");
284    /// assert_eq!(SmallBytes::new().as_slice(), b"");
285    /// ```
286    #[inline]
287    pub fn as_slice(&self) -> &[u8] {
288        if self.is_inline() {
289            // SAFETY: first `tag` bytes of `data` are valid (zero-init at construction).
290            unsafe { slice::from_raw_parts(self.inline.data.as_ptr(), self.inline.tag as usize) }
291        } else {
292            // SAFETY: heap variant active; ptr/len originate from a Vec or our own alloc.
293            unsafe { slice::from_raw_parts(self.heap.ptr.as_ptr(), self.heap.length()) }
294        }
295    }
296
297    /// Copy into a fresh `Vec<u8>` (clone semantics).
298    ///
299    /// # Examples
300    ///
301    /// ```
302    /// use kevy_bytes::SmallBytes;
303    /// let b = SmallBytes::from_slice(b"copy me");
304    /// assert_eq!(b.to_vec(), b"copy me");
305    /// assert_eq!(b.as_slice(), b"copy me", "the original still holds them");
306    /// ```
307    pub fn to_vec(&self) -> Vec<u8> {
308        self.as_slice().to_vec()
309    }
310
311    /// Consume self and return an owned `Vec<u8>`. The heap path reuses the
312    /// existing allocation; the inline path copies into a new vec.
313    ///
314    /// # Examples
315    ///
316    /// A heap value hands its buffer straight back, so a round trip through
317    /// `SmallBytes` costs no allocation at either end:
318    ///
319    /// ```
320    /// use kevy_bytes::SmallBytes;
321    /// let v = vec![b'q'; 128];
322    /// let addr = v.as_ptr();
323    /// assert_eq!(SmallBytes::from_vec(v).into_vec().as_ptr(), addr);
324    /// ```
325    ///
326    /// ```
327    /// use kevy_bytes::SmallBytes;
328    /// assert_eq!(SmallBytes::from_slice(b"short").into_vec(), b"short");
329    /// ```
330    pub fn into_vec(self) -> Vec<u8> {
331        if self.is_inline() {
332            self.as_slice().to_vec()
333            // self drops as inline — nothing to free.
334        } else {
335            // SAFETY: heap variant active.
336            let (ptr, len, cap) =
337                unsafe { (self.heap.ptr.as_ptr(), self.heap.length(), self.heap.capacity()) };
338            // Skip our Drop to avoid double-free; Vec::from_raw_parts now owns it.
339            let _do_not_drop = ManuallyDrop::new(self);
340            // SAFETY: ptr/len/cap originated from either a Vec<u8> (from_vec)
341            // or our own `alloc(Layout::array::<u8>(cap))` (alloc_heap, where
342            // cap == len) — both meet Vec::from_raw_parts' requirements.
343            unsafe { Vec::from_raw_parts(ptr, len, cap) }
344        }
345    }
346}
347
348impl Default for SmallBytes {
349    fn default() -> Self {
350        Self::new()
351    }
352}
353
354impl Drop for SmallBytes {
355    fn drop(&mut self) {
356        if self.is_inline() {
357            return;
358        }
359        // SAFETY: heap variant active; layout matches the one used at alloc
360        // time (either from Vec — Vec uses `Layout::array::<u8>(cap)` — or our
361        // own alloc_heap which used the same layout).
362        unsafe {
363            let cap = self.heap.capacity();
364            let layout = Layout::array::<u8>(cap).expect("kevy-bytes: drop layout");
365            dealloc(self.heap.ptr.as_ptr(), layout);
366        }
367    }
368}
369
370impl Clone for SmallBytes {
371    /// Specialised clone that bypasses `as_slice → from_slice → alloc_heap`'s
372    /// two layered length checks. Inline variant is a bitwise union copy (no
373    /// branch through the slice path); heap variant goes straight to a single
374    /// `alloc + memcpy` keyed on the already-known heap length.
375    #[inline]
376    fn clone(&self) -> Self {
377        if self.is_inline() {
378            // SAFETY: `Inline` is `repr(C)` + `Copy`; bitwise copy is sound
379            // when the source is currently in the inline variant (the tag
380            // byte ≤ 22 is part of the bit pattern we're copying, so the
381            // discriminator stays correct).
382            unsafe { Self { inline: self.inline } }
383        } else {
384            // SAFETY: tag > 22 ⇒ heap variant is active.
385            unsafe { self.clone_heap() }
386        }
387    }
388}
389
390impl SmallBytes {
391    /// Heap-fast-path clone. Caller must have established that `self` is in
392    /// the heap variant.
393    ///
394    /// # Safety
395    /// `self.heap` must be the active union variant (i.e. `is_inline()` is
396    /// false). `self.heap.ptr` must point to `self.heap.len` valid bytes.
397    #[inline]
398    unsafe fn clone_heap(&self) -> Self {
399        // SAFETY (covers the three `self.heap.*` reads): caller asserts the
400        // heap variant is active.
401        let (src_ptr, len) = unsafe { (self.heap.ptr.as_ptr(), self.heap.length()) };
402        // `len > 22 ⇒ len > 0`, and the high bits are guarded by `CAP_MASK`
403        // never letting cap exceed 2^56, well below `isize::MAX`, so the
404        // unchecked layout is sound. Allocator alignment for `u8` is 1.
405        let layout = unsafe { Layout::from_size_align_unchecked(len, 1) };
406        // SAFETY: layout.size() > 0.
407        let raw = unsafe { alloc(layout) };
408        let Some(ptr) = NonNull::new(raw) else { handle_alloc_error(layout) };
409        // SAFETY: src has `len` valid bytes; dst is freshly-allocated for `len`
410        // bytes; regions are disjoint.
411        unsafe { core::ptr::copy_nonoverlapping(src_ptr, ptr.as_ptr(), len) };
412        Self { heap: Heap::new(ptr, len, len) }
413    }
414}
415
416#[cfg(test)]
417mod tests;