1use std::borrow::Borrow;
4use std::cmp::Ordering;
5use std::fmt;
6use std::hash::{Hash, Hasher};
7use std::ops::Deref;
8
9use bytes::Bytes;
10
11const INLINE: usize = 23;
13
14#[derive(Clone)]
21pub struct Str(Repr);
22
23#[derive(Clone)]
24enum Repr {
25 Inline { len: u8, buf: [u8; INLINE] },
26 Static(&'static [u8]),
27 Shared(Bytes),
28}
29
30impl Str {
31 pub const EMPTY: Str = Str(Repr::Static(b""));
33
34 pub(crate) const INLINE: usize = INLINE;
36
37 pub const fn from_static(s: &'static str) -> Self {
39 Str(Repr::Static(s.as_bytes()))
40 }
41
42 pub const fn from_static_bytes(s: &'static [u8]) -> Self {
44 Str(Repr::Static(s))
45 }
46
47 pub fn from_bytes(b: Bytes) -> Self {
49 if b.len() <= INLINE { Self::inline(&b) } else { Str(Repr::Shared(b)) }
50 }
51
52 pub fn share(b: &Bytes, range: std::ops::Range<usize>) -> Self {
55 let len = range.len();
56 if len > INLINE {
57 return Str(Repr::Shared(b.slice(range)));
58 }
59 match b.get(range.start..range.start + INLINE) {
62 Some(window) if range.end <= b.len() => {
63 let mut buf = [0u8; INLINE];
64 buf.copy_from_slice(window);
65 Str(Repr::Inline { len: len as u8, buf })
66 }
67 _ => Self::inline(&b[range]),
68 }
69 }
70
71 pub fn copy_from(b: &[u8]) -> Self {
73 if b.len() <= INLINE { Self::inline(b) } else { Str(Repr::Shared(Bytes::copy_from_slice(b))) }
74 }
75
76 #[inline]
77 fn inline(b: &[u8]) -> Self {
78 let n = b.len();
79 debug_assert!(n <= INLINE);
80 let mut buf = [0u8; INLINE];
81 if n >= 16 {
84 buf[..16].copy_from_slice(&b[..16]);
85 buf[n - 8..n].copy_from_slice(&b[n - 8..]);
86 } else if n >= 8 {
87 buf[..8].copy_from_slice(&b[..8]);
88 buf[n - 8..n].copy_from_slice(&b[n - 8..]);
89 } else if n >= 4 {
90 buf[..4].copy_from_slice(&b[..4]);
91 buf[n - 4..n].copy_from_slice(&b[n - 4..]);
92 } else {
93 for (d, s) in buf.iter_mut().zip(b) {
94 *d = *s;
95 }
96 }
97 Str(Repr::Inline { len: n as u8, buf })
98 }
99
100 pub fn as_bytes(&self) -> &[u8] {
102 match &self.0 {
103 Repr::Inline { len, buf } => &buf[..*len as usize],
104 Repr::Static(s) => s,
105 Repr::Shared(b) => b,
106 }
107 }
108
109 pub fn as_str(&self) -> Option<&str> {
111 std::str::from_utf8(self.as_bytes()).ok()
112 }
113
114 pub fn len(&self) -> usize {
116 self.as_bytes().len()
117 }
118
119 pub fn is_empty(&self) -> bool {
121 self.len() == 0
122 }
123
124 pub fn to_bytes(&self) -> Bytes {
126 match &self.0 {
127 Repr::Shared(b) => b.clone(),
128 Repr::Static(s) => Bytes::from_static(s),
129 Repr::Inline { .. } => Bytes::copy_from_slice(self.as_bytes()),
130 }
131 }
132}
133
134impl Default for Str {
135 fn default() -> Self {
137 Str::EMPTY
138 }
139}
140
141impl Deref for Str {
142 type Target = [u8];
143
144 fn deref(&self) -> &[u8] {
146 self.as_bytes()
147 }
148}
149
150impl AsRef<[u8]> for Str {
151 fn as_ref(&self) -> &[u8] {
153 self.as_bytes()
154 }
155}
156
157impl Borrow<[u8]> for Str {
158 fn borrow(&self) -> &[u8] {
160 self.as_bytes()
161 }
162}
163
164impl PartialEq for Str {
165 fn eq(&self, other: &Self) -> bool {
167 self.as_bytes() == other.as_bytes()
168 }
169}
170
171impl Eq for Str {}
172
173impl PartialEq<[u8]> for Str {
174 fn eq(&self, other: &[u8]) -> bool {
176 self.as_bytes() == other
177 }
178}
179
180impl PartialEq<&[u8]> for Str {
181 fn eq(&self, other: &&[u8]) -> bool {
183 self.as_bytes() == *other
184 }
185}
186
187impl<const N: usize> PartialEq<&[u8; N]> for Str {
188 fn eq(&self, other: &&[u8; N]) -> bool {
190 self.as_bytes() == other.as_slice()
191 }
192}
193
194impl PartialEq<str> for Str {
195 fn eq(&self, other: &str) -> bool {
197 self.as_bytes() == other.as_bytes()
198 }
199}
200
201impl PartialEq<&str> for Str {
202 fn eq(&self, other: &&str) -> bool {
204 self.as_bytes() == other.as_bytes()
205 }
206}
207
208impl PartialOrd for Str {
209 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
211 Some(self.cmp(other))
212 }
213}
214
215impl Ord for Str {
217 fn cmp(&self, other: &Self) -> Ordering {
219 self.as_bytes().cmp(other.as_bytes())
220 }
221}
222
223impl Hash for Str {
225 fn hash<H: Hasher>(&self, state: &mut H) {
227 self.as_bytes().hash(state);
228 }
229}
230
231impl fmt::Debug for Str {
232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 fmt::Debug::fmt(&String::from_utf8_lossy(self.as_bytes()), f)
235 }
236}
237
238impl From<&str> for Str {
239 fn from(s: &str) -> Self {
241 Str::copy_from(s.as_bytes())
242 }
243}
244
245impl From<String> for Str {
246 fn from(s: String) -> Self {
248 Str::from(s.into_bytes())
249 }
250}
251
252impl From<&[u8]> for Str {
253 fn from(s: &[u8]) -> Self {
255 Str::copy_from(s)
256 }
257}
258
259impl From<Vec<u8>> for Str {
260 fn from(s: Vec<u8>) -> Self {
262 if s.len() <= INLINE { Str::inline(&s) } else { Str(Repr::Shared(Bytes::from(s))) }
263 }
264}
265
266impl From<Bytes> for Str {
267 fn from(b: Bytes) -> Self {
269 Str::from_bytes(b)
270 }
271}
272
273#[cfg(test)]
274mod tests {
275 use super::*;
276
277 #[test]
278 fn representations_are_invisible() {
279 let long = "x".repeat(40);
280 for s in [Str::from("abc"), Str::from_static("abc"), Str::from_bytes(Bytes::from_static(b"abc"))] {
281 assert_eq!(s, *"abc");
282 assert_eq!(s.len(), 3);
283 }
284 assert_eq!(Str::from(long.clone()), Str::from_static(Box::leak(long.into_boxed_str())));
285 assert!(Str::EMPTY.is_empty());
286 assert_eq!(Str::copy_from(b"\xff").as_str(), None);
287 }
288}