Skip to main content

kevy_bytes/
traits.rs

1//! Trait impls for [`SmallBytes`] that only need the public byte-slice
2//! view (`as_slice()`). The discriminator-aware `PartialEq` / `Eq` stay
3//! in `lib.rs` next to the union definition because they reach into
4//! `self.inline` / `self.heap` directly for the same-variant fast paths.
5
6use std::cmp::Ordering;
7use std::fmt;
8use std::hash::{Hash, Hasher};
9
10use crate::SmallBytes;
11
12impl fmt::Debug for SmallBytes {
13    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14        // Match Vec<u8>'s Debug ("[1, 2, 3]" form).
15        f.debug_list().entries(self.as_slice().iter()).finish()
16    }
17}
18
19impl PartialOrd for SmallBytes {
20    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
21        Some(self.cmp(other))
22    }
23}
24
25impl Ord for SmallBytes {
26    fn cmp(&self, other: &Self) -> Ordering {
27        self.as_slice().cmp(other.as_slice())
28    }
29}
30
31impl Hash for SmallBytes {
32    fn hash<H: Hasher>(&self, state: &mut H) {
33        self.as_slice().hash(state);
34    }
35}
36
37impl AsRef<[u8]> for SmallBytes {
38    fn as_ref(&self) -> &[u8] {
39        self.as_slice()
40    }
41}
42
43impl std::borrow::Borrow<[u8]> for SmallBytes {
44    fn borrow(&self) -> &[u8] {
45        self.as_slice()
46    }
47}
48
49/// `KevyHash` agrees with the byte-slice impl, so a `KevyMap<SmallBytes, V>`
50/// can be queried with `&[u8]` (via `Borrow<[u8]>`) and the hash matches.
51impl kevy_hash::KevyHash for SmallBytes {
52    #[inline]
53    fn kevy_hash(&self) -> u64 {
54        self.as_slice().kevy_hash()
55    }
56}
57
58impl From<&[u8]> for SmallBytes {
59    fn from(bytes: &[u8]) -> Self {
60        Self::from_slice(bytes)
61    }
62}
63
64impl From<Vec<u8>> for SmallBytes {
65    fn from(vec: Vec<u8>) -> Self {
66        Self::from_vec(vec)
67    }
68}