Skip to main content

waratah_storage/encode/
small_string.rs

1//! Inline UTF-8 strings up to 15 bytes (Oxigraph-compatible wire layout).
2
3use std::borrow::Borrow;
4use std::cmp::Ordering;
5use std::fmt;
6use std::hash::{Hash, Hasher};
7use std::ops::Deref;
8use std::str::{self, FromStr, Utf8Error};
9
10/// A small inline string stored in 16 bytes (payload + length in byte 15).
11#[derive(Clone, Copy, Default)]
12pub struct SmallString {
13    inner: [u8; 16],
14}
15
16/// Error building a [`SmallString`].
17#[derive(Debug, Clone, Copy, thiserror::Error)]
18pub enum BadSmallStringError {
19    /// String exceeds the 15-character inline limit.
20    #[error("small strings could only contain at most 15 characters, found {0}")]
21    TooLong(usize),
22    /// Invalid UTF-8.
23    #[error(transparent)]
24    BadUtf8(#[from] Utf8Error),
25}
26
27impl SmallString {
28    /// Empty inline string.
29    #[inline]
30    pub const fn new() -> Self {
31        Self { inner: [0; 16] }
32    }
33
34    /// Parse from big-endian wire bytes.
35    #[inline]
36    pub fn from_be_bytes(bytes: [u8; 16]) -> Result<Self, BadSmallStringError> {
37        str::from_utf8(&bytes[..bytes[15].into()]).map_err(BadSmallStringError::BadUtf8)?;
38        Ok(Self { inner: bytes })
39    }
40
41    /// UTF-8 length in bytes.
42    #[inline]
43    pub fn len(&self) -> usize {
44        self.inner[15].into()
45    }
46
47    /// Whether the string is empty.
48    #[inline]
49    pub fn is_empty(&self) -> bool {
50        self.len() == 0
51    }
52
53    /// View as `&str` (validated at construction).
54    #[inline]
55    pub fn as_str(&self) -> &str {
56        // SAFETY: constructors validate UTF-8 over `0..len`.
57        unsafe { str::from_utf8_unchecked(self.as_bytes()) }
58    }
59
60    /// Payload bytes without the length suffix.
61    #[inline]
62    pub fn as_bytes(&self) -> &[u8] {
63        &self.inner[..self.len()]
64    }
65
66    /// Serialize to big-endian wire form.
67    #[inline]
68    pub fn to_be_bytes(self) -> [u8; 16] {
69        self.inner
70    }
71}
72
73impl Deref for SmallString {
74    type Target = str;
75
76    #[inline]
77    fn deref(&self) -> &Self::Target {
78        self.as_str()
79    }
80}
81
82impl AsRef<str> for SmallString {
83    #[inline]
84    fn as_ref(&self) -> &str {
85        self.as_str()
86    }
87}
88
89impl Borrow<str> for SmallString {
90    #[inline]
91    fn borrow(&self) -> &str {
92        self.as_str()
93    }
94}
95
96impl fmt::Debug for SmallString {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        self.as_str().fmt(f)
99    }
100}
101
102impl fmt::Display for SmallString {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        self.as_str().fmt(f)
105    }
106}
107
108impl PartialEq for SmallString {
109    fn eq(&self, other: &Self) -> bool {
110        self.as_str() == other.as_str()
111    }
112}
113
114impl Eq for SmallString {}
115
116impl PartialOrd for SmallString {
117    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
118        Some(self.cmp(other))
119    }
120}
121
122impl Ord for SmallString {
123    fn cmp(&self, other: &Self) -> Ordering {
124        self.as_str().cmp(other.as_str())
125    }
126}
127
128impl Hash for SmallString {
129    fn hash<H: Hasher>(&self, state: &mut H) {
130        self.as_str().hash(state);
131    }
132}
133
134impl FromStr for SmallString {
135    type Err = BadSmallStringError;
136
137    fn from_str(value: &str) -> Result<Self, Self::Err> {
138        if value.len() <= 15 {
139            let mut inner = [0; 16];
140            inner[..value.len()].copy_from_slice(value.as_bytes());
141            inner[15] = value
142                .len()
143                .try_into()
144                .map_err(|_| Self::Err::TooLong(value.len()))?;
145            Ok(Self { inner })
146        } else {
147            Err(Self::Err::TooLong(value.len()))
148        }
149    }
150}
151
152impl<'a> TryFrom<&'a str> for SmallString {
153    type Error = BadSmallStringError;
154
155    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
156        Self::from_str(value)
157    }
158}