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 alloc::vec::Vec;
7use core::cmp::Ordering;
8use core::fmt;
9use core::hash::{Hash, Hasher};
10
11use crate::SmallBytes;
12
13impl fmt::Debug for SmallBytes {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        // Match Vec<u8>'s Debug ("[1, 2, 3]" form).
16        f.debug_list().entries(self.as_slice().iter()).finish()
17    }
18}
19
20impl PartialOrd for SmallBytes {
21    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
22        Some(self.cmp(other))
23    }
24}
25
26impl Ord for SmallBytes {
27    fn cmp(&self, other: &Self) -> Ordering {
28        self.as_slice().cmp(other.as_slice())
29    }
30}
31
32impl Hash for SmallBytes {
33    fn hash<H: Hasher>(&self, state: &mut H) {
34        self.as_slice().hash(state);
35    }
36}
37
38impl AsRef<[u8]> for SmallBytes {
39    fn as_ref(&self) -> &[u8] {
40        self.as_slice()
41    }
42}
43
44impl core::borrow::Borrow<[u8]> for SmallBytes {
45    fn borrow(&self) -> &[u8] {
46        self.as_slice()
47    }
48}
49
50/// `KevyHash` agrees with the byte-slice impl, so a `KevyMap<SmallBytes, V>`
51/// can be queried with `&[u8]` (via `Borrow<[u8]>`) and the hash matches.
52impl kevy_hash::KevyHash for SmallBytes {
53    #[inline]
54    fn kevy_hash(&self) -> u64 {
55        self.as_slice().kevy_hash()
56    }
57}
58
59impl From<&[u8]> for SmallBytes {
60    fn from(bytes: &[u8]) -> Self {
61        Self::from_slice(bytes)
62    }
63}
64
65impl From<Vec<u8>> for SmallBytes {
66    fn from(vec: Vec<u8>) -> Self {
67        Self::from_vec(vec)
68    }
69}