Skip to main content

php_std/types/
str.rs

1//! [`Str`]: a PHP string, which is a byte string.
2
3use std::borrow::Borrow;
4use std::cmp::Ordering;
5use std::fmt;
6use std::hash::{Hash, Hasher};
7use std::ops::Deref;
8
9use bytes::Bytes;
10
11/// The longest string kept inline, without an allocation.
12const INLINE: usize = 23;
13
14/// A PHP string: bytes, not necessarily UTF-8.
15///
16/// Three representations, chosen on construction and invisible otherwise:
17/// short strings (up to 23 bytes) are stored inline, string literals borrow
18/// their `'static` bytes, and longer strings share a [`Bytes`] buffer, so
19/// clones and slices of decoded input never copy.
20#[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    /// The empty string.
32    pub const EMPTY: Str = Str(Repr::Static(b""));
33
34    /// The longest string kept inline, without an allocation.
35    pub(crate) const INLINE: usize = INLINE;
36
37    /// A string literal (no allocation, no copy).
38    pub const fn from_static(s: &'static str) -> Self {
39        Str(Repr::Static(s.as_bytes()))
40    }
41
42    /// Static bytes (no allocation, no copy).
43    pub const fn from_static_bytes(s: &'static [u8]) -> Self {
44        Str(Repr::Static(s))
45    }
46
47    /// Shares `b` (short strings are copied inline instead).
48    pub fn from_bytes(b: Bytes) -> Self {
49        if b.len() <= INLINE { Self::inline(&b) } else { Str(Repr::Shared(b)) }
50    }
51
52    /// The bytes of `b` in `range`: shared, or copied inline when short
53    /// (without touching `b`'s reference count).
54    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        // A whole buffer's worth when the input has it: one fixed-size copy
60        // rather than a variable one (bytes past `len` are never read).
61        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    /// Copies `b`.
72    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        // Two overlapping fixed-size copies instead of a `memcpy` call: short
82        // strings are what decoders make most.
83        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    /// The bytes of the string.
101    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    /// The string as UTF-8 text, when it is valid UTF-8.
110    pub fn as_str(&self) -> Option<&str> {
111        std::str::from_utf8(self.as_bytes()).ok()
112    }
113
114    /// The length in bytes.
115    pub fn len(&self) -> usize {
116        self.as_bytes().len()
117    }
118
119    /// Whether the string is empty.
120    pub fn is_empty(&self) -> bool {
121        self.len() == 0
122    }
123
124    /// The bytes as a shared buffer (a copy only for inline and static strings).
125    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    /// The empty string.
136    fn default() -> Self {
137        Str::EMPTY
138    }
139}
140
141impl Deref for Str {
142    type Target = [u8];
143
144    /// The bytes of the string.
145    fn deref(&self) -> &[u8] {
146        self.as_bytes()
147    }
148}
149
150impl AsRef<[u8]> for Str {
151    /// The bytes of the string.
152    fn as_ref(&self) -> &[u8] {
153        self.as_bytes()
154    }
155}
156
157impl Borrow<[u8]> for Str {
158    /// The bytes of the string, so maps keyed by `Str` can be queried with `&[u8]`.
159    fn borrow(&self) -> &[u8] {
160        self.as_bytes()
161    }
162}
163
164impl PartialEq for Str {
165    /// Whether both hold the same bytes.
166    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    /// Whether the string holds these bytes.
175    fn eq(&self, other: &[u8]) -> bool {
176        self.as_bytes() == other
177    }
178}
179
180impl PartialEq<&[u8]> for Str {
181    /// Whether the string holds these bytes.
182    fn eq(&self, other: &&[u8]) -> bool {
183        self.as_bytes() == *other
184    }
185}
186
187impl<const N: usize> PartialEq<&[u8; N]> for Str {
188    /// Whether the string holds these bytes (a byte string literal).
189    fn eq(&self, other: &&[u8; N]) -> bool {
190        self.as_bytes() == other.as_slice()
191    }
192}
193
194impl PartialEq<str> for Str {
195    /// Whether the string holds the bytes of `other`.
196    fn eq(&self, other: &str) -> bool {
197        self.as_bytes() == other.as_bytes()
198    }
199}
200
201impl PartialEq<&str> for Str {
202    /// Whether the string holds the bytes of `other`.
203    fn eq(&self, other: &&str) -> bool {
204        self.as_bytes() == other.as_bytes()
205    }
206}
207
208impl PartialOrd for Str {
209    /// Byte order, as [`Ord`].
210    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
211        Some(self.cmp(other))
212    }
213}
214
215/// Byte order (`strcmp`), not PHP's `<=>` (see [`crate::types::Value::cmp_php`]).
216impl Ord for Str {
217    /// Compares the bytes (`strcmp` order).
218    fn cmp(&self, other: &Self) -> Ordering {
219        self.as_bytes().cmp(other.as_bytes())
220    }
221}
222
223/// Hashes like `[u8]`, so maps keyed by `Str` can be queried with `&[u8]`.
224impl Hash for Str {
225    /// Hashes the bytes, as `[u8]` does.
226    fn hash<H: Hasher>(&self, state: &mut H) {
227        self.as_bytes().hash(state);
228    }
229}
230
231impl fmt::Debug for Str {
232    /// Writes the string quoted, with invalid UTF-8 replaced.
233    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    /// Copies the bytes of `s`.
240    fn from(s: &str) -> Self {
241        Str::copy_from(s.as_bytes())
242    }
243}
244
245impl From<String> for Str {
246    /// Takes the bytes of `s`.
247    fn from(s: String) -> Self {
248        Str::from(s.into_bytes())
249    }
250}
251
252impl From<&[u8]> for Str {
253    /// Copies `s`.
254    fn from(s: &[u8]) -> Self {
255        Str::copy_from(s)
256    }
257}
258
259impl From<Vec<u8>> for Str {
260    /// Takes `s` (short strings are copied inline).
261    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    /// Shares `b`, as [`Str::from_bytes`].
268    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}