Skip to main content

zcheapstr/
str.rs

1#[cfg(feature = "serde")]
2use serde::{Deserialize, Deserializer, Serialize, Serializer};
3
4use alloc::{borrow::Cow, string::String, sync::Arc};
5use core::{
6    cmp::Ordering,
7    hash::{Hash, Hasher},
8    ptr::NonNull,
9};
10
11/// A string wrapper.
12///
13///
14/// This is similar to the [`Cow`] type, but it:
15///
16/// * is specialized for strings.
17/// * treats `&'static str` as a separate type. This allows you to avoid allocations and copying
18///   when turning a `CheapStr` instance created from a `&'static str` into an owned version in
19///   generic code that doesn't/can't assume the inner lifetime of the source `CheapStr` instance.
20/// * stores owned strings in an [`Arc`], so `Clone` never copies or allocates: it either copies a
21///   reference or increments a reference count.
22/// * is immutable. Consequently, unlike [`Cow`], it is *not* a copy-on-write type: there is no way
23///   to get a mutable reference to the underlying string.
24///
25/// API is provided to convert from, and to a [`&str`] and [`String`].
26///
27/// [`&str`]: https://doc.rust-lang.org/std/str/index.html
28/// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
29#[derive(Default, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
31pub struct CheapStr<'a>(#[cfg_attr(feature = "serde", serde(borrow))] Inner<'a>);
32
33#[derive(Clone)]
34enum Inner<'a> {
35    Static(&'static str),
36    Borrowed(&'a str),
37    Owned(ArcStr),
38}
39
40impl Default for Inner<'_> {
41    fn default() -> Self {
42        Self::Static("")
43    }
44}
45
46impl<'a> PartialEq for Inner<'a> {
47    fn eq(&self, other: &Inner<'a>) -> bool {
48        self.as_str() == other.as_str()
49    }
50}
51
52impl Eq for Inner<'_> {}
53
54impl<'a> Ord for Inner<'a> {
55    fn cmp(&self, other: &Inner<'a>) -> Ordering {
56        self.as_str().cmp(other.as_str())
57    }
58}
59
60impl<'a> PartialOrd for Inner<'a> {
61    fn partial_cmp(&self, other: &Inner<'a>) -> Option<Ordering> {
62        Some(self.cmp(other))
63    }
64}
65
66impl Hash for Inner<'_> {
67    fn hash<H: Hasher>(&self, h: &mut H) {
68        self.as_str().hash(h)
69    }
70}
71
72impl Inner<'_> {
73    /// The underlying string.
74    pub const fn as_str(&self) -> &str {
75        match self {
76            Inner::Static(s) => s,
77            Inner::Borrowed(s) => s,
78            Inner::Owned(s) => s.as_str(),
79        }
80    }
81}
82
83#[cfg(feature = "serde")]
84impl Serialize for Inner<'_> {
85    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
86        s.serialize_str(self.as_str())
87    }
88}
89
90#[cfg(feature = "serde")]
91impl<'de: 'a, 'a> Deserialize<'de> for Inner<'a> {
92    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
93    where
94        D: Deserializer<'de>,
95    {
96        <&'a str>::deserialize(deserializer).map(Inner::Borrowed)
97    }
98}
99
100impl CheapStr<'_> {
101    /// An owned string without allocations
102    pub const fn from_static(s: &'static str) -> Self {
103        CheapStr(Inner::Static(s))
104    }
105
106    /// This is faster than `Clone::clone` when `self` contains owned data.
107    pub fn as_ref(&self) -> CheapStr<'_> {
108        match &self.0 {
109            Inner::Static(s) => CheapStr(Inner::Static(s)),
110            Inner::Borrowed(s) => CheapStr(Inner::Borrowed(s)),
111            Inner::Owned(s) => CheapStr(Inner::Borrowed(s.as_str())),
112        }
113    }
114
115    /// The underlying string.
116    ///
117    /// This is a `const fn`. As `CheapStr` has a destructor, which can't run in `const` context,
118    /// `const` code can only call it on an instance that is never dropped, such as one behind a
119    /// `const` reference or in a `static`:
120    ///
121    /// ```
122    /// use zcheapstr::CheapStr;
123    ///
124    /// const NAME: &CheapStr<'static> = &CheapStr::from_static("zcheapstr");
125    /// const NAME_STR: &str = NAME.as_str();
126    /// assert_eq!(NAME_STR, "zcheapstr");
127    /// ```
128    pub const fn as_str(&self) -> &str {
129        self.0.as_str()
130    }
131
132    /// Creates an owned clone of `self`.
133    pub fn to_owned(&self) -> CheapStr<'static> {
134        self.clone().into_owned()
135    }
136
137    /// Creates an owned clone of `self`.
138    pub fn into_owned(self) -> CheapStr<'static> {
139        match self.0 {
140            Inner::Static(s) => CheapStr(Inner::Static(s)),
141            Inner::Borrowed(s) => CheapStr::from(Arc::<str>::from(s)),
142            Inner::Owned(s) => CheapStr(Inner::Owned(s)),
143        }
144    }
145}
146
147impl<'a> From<&'a str> for CheapStr<'a> {
148    fn from(value: &'a str) -> Self {
149        Self(Inner::Borrowed(value))
150    }
151}
152
153impl<'a> From<&'a String> for CheapStr<'a> {
154    fn from(value: &'a String) -> Self {
155        Self(Inner::Borrowed(value))
156    }
157}
158
159impl From<String> for CheapStr<'_> {
160    fn from(value: String) -> Self {
161        Self::from(Arc::<str>::from(value))
162    }
163}
164
165impl From<Arc<str>> for CheapStr<'_> {
166    fn from(value: Arc<str>) -> Self {
167        Self(Inner::Owned(ArcStr::from(value)))
168    }
169}
170
171impl<'a> From<Cow<'a, str>> for CheapStr<'a> {
172    fn from(value: Cow<'a, str>) -> Self {
173        match value {
174            Cow::Owned(value) => value.into(),
175            Cow::Borrowed(value) => value.into(),
176        }
177    }
178}
179
180impl<'a> From<CheapStr<'a>> for String {
181    fn from(value: CheapStr<'a>) -> String {
182        match value.0 {
183            Inner::Static(s) => s.into(),
184            Inner::Borrowed(s) => s.into(),
185            Inner::Owned(s) => s.as_str().into(),
186        }
187    }
188}
189
190impl<'a> From<&'a CheapStr<'_>> for &'a str {
191    fn from(value: &'a CheapStr<'_>) -> &'a str {
192        value.as_str()
193    }
194}
195
196impl core::ops::Deref for CheapStr<'_> {
197    type Target = str;
198
199    fn deref(&self) -> &Self::Target {
200        self.as_str()
201    }
202}
203
204impl PartialEq<str> for CheapStr<'_> {
205    fn eq(&self, other: &str) -> bool {
206        self.as_str() == other
207    }
208}
209
210impl PartialEq<&str> for CheapStr<'_> {
211    fn eq(&self, other: &&str) -> bool {
212        self.as_str() == *other
213    }
214}
215
216impl core::fmt::Debug for CheapStr<'_> {
217    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
218        core::fmt::Debug::fmt(self.as_str(), f)
219    }
220}
221
222impl core::fmt::Display for CheapStr<'_> {
223    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
224        core::fmt::Display::fmt(self.as_str(), f)
225    }
226}
227
228/// An `Arc<str>`, held as the pointer to its string.
229///
230/// `Arc` offers no way to reach its data in `const` context, while a pointer can be dereferenced
231/// there. Holding the pointer that `Arc::into_raw` returns, instead of the `Arc` itself, is what
232/// allows [`CheapStr::as_str`] to be a `const fn`.
233///
234/// The unsafe code below relies on this invariant: the pointer is one that `Arc::<str>::into_raw`
235/// returned, and the `ArcStr` owns one strong reference to that `Arc`. `From` sets it up, taking
236/// over the reference of the `Arc` it is given, `Clone` adds a reference for the clone to own and
237/// `Drop` gives the reference back. Nothing else creates an `ArcStr`, changes its pointer or
238/// touches the reference counts, and as neither the type nor its field is visible outside of this
239/// file, no other code can.
240struct ArcStr(NonNull<str>);
241
242impl ArcStr {
243    const fn as_str(&self) -> &str {
244        // SAFETY: By the invariant, the pointer points to the string of an `Arc` that `self` owns
245        // a strong reference to. The returned reference borrows `self`, so `self` and its strong
246        // reference outlive it, which keeps the string allocated. Nothing can change the string
247        // meanwhile either: `str` has no interior mutability, and `Arc` only grants mutable access
248        // to its data when no other `Arc` or `Weak` points to the same allocation, which the strong
249        // reference of `self` rules out.
250        unsafe { self.0.as_ref() }
251    }
252}
253
254impl From<Arc<str>> for ArcStr {
255    fn from(value: Arc<str>) -> Self {
256        // `into_raw` doesn't give back the strong reference of `value`: the `ArcStr` takes it over.
257        let ptr = Arc::into_raw(value).cast_mut();
258        // SAFETY: `Arc::into_raw` never returns a null pointer, as it points to the data inside the
259        // allocation of the `Arc`.
260        Self(unsafe { NonNull::new_unchecked(ptr) })
261    }
262}
263
264impl Clone for ArcStr {
265    fn clone(&self) -> Self {
266        // SAFETY: By the invariant, the pointer is one that `Arc::<str>::into_raw` returned, so it
267        // has the layout that `Arc<str>` requires and points into memory of the global allocator,
268        // which `Arc<str>` uses. The strong reference of `self` keeps that `Arc` alive throughout.
269        // The clone owns the reference that this adds, which upholds the invariant for it.
270        unsafe { Arc::increment_strong_count(self.0.as_ptr()) };
271
272        Self(self.0)
273    }
274}
275
276impl Drop for ArcStr {
277    fn drop(&mut self) {
278        // SAFETY: By the invariant, the pointer is one that `Arc::<str>::into_raw` returned, and
279        // `self` owns a strong reference to that `Arc`. The rebuilt `Arc` takes that reference over
280        // and gives it back as it is dropped here. As `self` is never used again, and every
281        // `ArcStr` owns a reference of its own, each reference is given back exactly once.
282        drop(unsafe { Arc::from_raw(self.0.as_ptr()) });
283    }
284}
285
286// SAFETY: An `ArcStr` uses its pointer only to read the string, which can't change (see
287// `ArcStr::as_str`), and to change the reference counts of the `Arc`, which `Arc` does atomically.
288// So it can be sent to, and dropped on, another thread like the `Arc<str>` it stands for, which is
289// `Send` as `str` is `Send` and `Sync`.
290unsafe impl Send for ArcStr {}
291
292// SAFETY: A shared `ArcStr` can only be read, or cloned, which adds a strong reference atomically.
293// So it can be shared between threads like the `Arc<str>` it stands for, which is `Sync` as `str`
294// is `Send` and `Sync`.
295unsafe impl Sync for ArcStr {}
296
297#[cfg(test)]
298mod tests {
299    use super::CheapStr;
300    use alloc::{
301        string::{String, ToString},
302        sync::Arc,
303    };
304    use core::panic::{RefUnwindSafe, UnwindSafe};
305
306    #[test]
307    fn from_string() {
308        let string = String::from("value");
309        let v = CheapStr::from(&string);
310        assert_eq!(v.as_str(), "value");
311    }
312
313    #[test]
314    fn test_ordering() {
315        let first = CheapStr::from("a".to_string());
316        let second = CheapStr::from_static("b");
317        assert!(first < second);
318    }
319
320    #[test]
321    fn as_str_in_const() {
322        const STATIC: &CheapStr<'static> = &CheapStr::from_static("static");
323        const STATIC_STR: &str = STATIC.as_str();
324        assert_eq!(STATIC_STR, "static");
325    }
326
327    #[test]
328    fn shared_data() {
329        let arc = Arc::<str>::from("shared");
330        let s = CheapStr::from(arc.clone());
331        assert_eq!(s.as_str(), "shared");
332        assert_eq!(Arc::strong_count(&arc), 2);
333
334        // Neither cloning nor turning into an owned instance copies the string.
335        let clone = s.clone();
336        assert_eq!(Arc::strong_count(&arc), 3);
337        assert!(core::ptr::eq(clone.as_str(), &*arc));
338        let owned = s.into_owned();
339        assert_eq!(Arc::strong_count(&arc), 3);
340        assert!(core::ptr::eq(owned.as_str(), &*arc));
341
342        drop(clone);
343        assert_eq!(String::from(owned), "shared");
344        assert_eq!(Arc::strong_count(&arc), 1);
345    }
346
347    #[test]
348    fn auto_traits() {
349        fn assert_auto_traits<T>()
350        where
351            T: Send + Sync + Unpin + UnwindSafe + RefUnwindSafe,
352        {
353        }
354
355        assert_auto_traits::<CheapStr<'_>>();
356    }
357}
358
359#[cfg(all(test, feature = "serde"))]
360mod serde_tests {
361    use super::CheapStr;
362    use alloc::string::String;
363
364    #[test]
365    fn serde_round_trip() {
366        let s = CheapStr::from("hello");
367        let json = serde_json::to_string(&s).unwrap();
368        assert_eq!(json, "\"hello\"");
369        let deserialized: CheapStr<'_> = serde_json::from_str(&json).unwrap();
370        assert_eq!(deserialized, s);
371
372        // Owned data serializes the same way.
373        let owned = CheapStr::from(String::from("hello"));
374        assert_eq!(serde_json::to_string(&owned).unwrap(), json);
375    }
376
377    #[test]
378    fn serde_non_borrowable_input_errors() {
379        // `CheapStr` only supports borrowed deserialization: input that cannot be handed out as a
380        // borrowed `&str` (here because of the escape sequence) is an error, not an allocation.
381        serde_json::from_str::<CheapStr<'_>>("\"a\\nb\"").unwrap_err();
382    }
383
384    #[test]
385    fn serde_borrowed_deserialization() {
386        let json = String::from("\"borrowed\"");
387        let s: CheapStr<'_> = serde_json::from_str(&json).unwrap();
388        assert_eq!(s.as_str(), "borrowed");
389        // The deserialized `CheapStr` borrows from the JSON input instead of allocating.
390        assert!(core::ptr::eq(s.as_str().as_ptr(), json[1..].as_ptr()));
391    }
392}