turbo_rcstr/
lib.rs

1use std::{
2    borrow::{Borrow, Cow},
3    ffi::OsStr,
4    fmt::{Debug, Display},
5    hash::{Hash, Hasher},
6    mem::{ManuallyDrop, forget},
7    num::NonZeroU8,
8    ops::Deref,
9    path::{Path, PathBuf},
10};
11
12use bincode::{
13    Decode, Encode,
14    de::Decoder,
15    enc::Encoder,
16    error::{DecodeError, EncodeError},
17    impl_borrow_decode,
18};
19use bytes_str::BytesStr;
20use debug_unreachable::debug_unreachable;
21use serde::{Deserialize, Deserializer, Serialize, Serializer};
22use shrink_to_fit::ShrinkToFit;
23use triomphe::Arc;
24use turbo_tasks_hash::{DeterministicHash, DeterministicHasher};
25
26use crate::{
27    dynamic::{deref_from, hash_bytes, new_atom},
28    tagged_value::TaggedValue,
29};
30
31mod dynamic;
32mod tagged_value;
33
34/// An immutable reference counted [`String`], similar to [`Arc<String>`][std::sync::Arc].
35///
36/// This is the preferred immutable string type for [`turbo_tasks::function`][func] arguments and
37/// inside of [`turbo_tasks::value`][value].
38///
39/// As turbo-tasks must store copies of function arguments to enable caching, non-reference counted
40/// [`String`]s would incur frequent cloning. Reference counting typically decreases memory
41/// consumption and CPU time in these cases.
42///
43/// [func]: https://turbopack-rust-docs.vercel.sh/rustdoc/turbo_tasks/attr.function.html
44/// [value]: https://turbopack-rust-docs.vercel.sh/rustdoc/turbo_tasks/attr.value.html
45///
46/// ## Conversion
47///
48/// Converting a `String` or `&str` to an `RcStr` can be performed using `.into()`,
49/// `RcStr::from(...)`, or the `rcstr!` macro.
50///
51/// ```
52/// # use turbo_rcstr::RcStr;
53/// #
54/// let s = "foo";
55/// let rc_s1: RcStr = s.into();
56/// let rc_s2 = RcStr::from(s);
57/// let rc_s3 = rcstr!("foo");
58/// assert_eq!(rc_s1, rc_s2);
59/// ```
60///
61/// Generally speaking you should
62///  * use `rcstr!` when converting a `const`-compatible `str`
63///  * use `RcStr::from` for readability
64///  * use `.into()` when context makes it clear.
65///
66/// Converting from an [`RcStr`] to a `&str` should be done with [`RcStr::as_str`]. Converting to a
67/// `String` should be done with [`RcStr::into_owned`].
68///
69/// ## Future Optimizations
70///
71/// This type is intentionally opaque to allow for optimizations to the underlying representation.
72/// Future implementations may use inline representations or interning.
73//
74// If you want to change the underlying string type to `Arc<str>`, please ensure that you profile
75// performance. The current implementation offers very cheap `String -> RcStr -> String`, meaning we
76// only pay for the allocation for `Arc` when we pass `format!("").into()` to a function.
77pub struct RcStr {
78    unsafe_data: TaggedValue,
79}
80
81const _: () = {
82    // Enforce that RcStr triggers the non-zero size optimization.
83    assert!(std::mem::size_of::<RcStr>() == std::mem::size_of::<Option<RcStr>>());
84};
85
86unsafe impl Send for RcStr {}
87unsafe impl Sync for RcStr {}
88
89// Marks a payload that is stored in an Arc
90const DYNAMIC_TAG: u8 = 0b_00;
91const PREHASHED_STRING_LOCATION: u8 = 0b_0;
92// Marks a payload that has been leaked since it has a static lifetime
93const STATIC_TAG: u8 = 0b_10;
94// The payload is stored inline
95const INLINE_TAG: u8 = 0b_01; // len in upper nybble
96const INLINE_LOCATION: u8 = 0b_1;
97const INLINE_TAG_INIT: NonZeroU8 = NonZeroU8::new(INLINE_TAG).unwrap();
98const TAG_MASK: u8 = 0b_11;
99const LOCATION_MASK: u8 = 0b_1;
100// For inline tags the length is stored in the upper 4 bits of the tag byte
101const LEN_OFFSET: usize = 4;
102const LEN_MASK: u8 = 0xf0;
103
104impl RcStr {
105    #[inline(always)]
106    fn tag(&self) -> u8 {
107        self.unsafe_data.tag_byte() & TAG_MASK
108    }
109    #[inline(always)]
110    fn location(&self) -> u8 {
111        self.unsafe_data.tag_byte() & LOCATION_MASK
112    }
113
114    #[inline(never)]
115    pub fn as_str(&self) -> &str {
116        match self.location() {
117            PREHASHED_STRING_LOCATION => self.prehashed_string_as_str(),
118            INLINE_LOCATION => self.inline_as_str(),
119            _ => unsafe { debug_unreachable!() },
120        }
121    }
122
123    fn inline_as_str(&self) -> &str {
124        debug_assert!(self.location() == INLINE_LOCATION);
125        let len = (self.unsafe_data.tag_byte() & LEN_MASK) >> LEN_OFFSET;
126        let src = self.unsafe_data.data();
127        unsafe { std::str::from_utf8_unchecked(&src[..(len as usize)]) }
128    }
129
130    // Extract the str reference from a string stored in a PrehashedString
131    fn prehashed_string_as_str(&self) -> &str {
132        debug_assert!(self.location() == PREHASHED_STRING_LOCATION);
133        unsafe { dynamic::deref_from(self.unsafe_data).value.as_str() }
134    }
135
136    /// Returns an owned mutable [`String`].
137    ///
138    /// This implementation is more efficient than [`ToString::to_string`]:
139    ///
140    /// - If the reference count is 1, the `Arc` can be unwrapped, giving ownership of the
141    ///   underlying string without cloning in `O(1)` time.
142    /// - This avoids some of the potential overhead of the `Display` trait.
143    pub fn into_owned(self) -> String {
144        match self.tag() {
145            DYNAMIC_TAG => {
146                // convert `self` into `arc`
147                let arc = unsafe { dynamic::restore_arc(ManuallyDrop::new(self).unsafe_data) };
148                match Arc::try_unwrap(arc) {
149                    Ok(v) => v.value.into_string(),
150                    Err(arc) => arc.value.as_str().to_string(),
151                }
152            }
153            INLINE_TAG => self.inline_as_str().to_string(),
154            STATIC_TAG => self.prehashed_string_as_str().to_string(),
155            _ => unsafe { debug_unreachable!() },
156        }
157    }
158
159    pub fn map(self, f: impl FnOnce(String) -> String) -> Self {
160        RcStr::from(Cow::Owned(f(self.into_owned())))
161    }
162}
163
164impl DeterministicHash for RcStr {
165    fn deterministic_hash<H: DeterministicHasher>(&self, state: &mut H) {
166        state.write_usize(self.len());
167        state.write_bytes(self.as_bytes());
168    }
169}
170
171impl Deref for RcStr {
172    type Target = str;
173
174    fn deref(&self) -> &Self::Target {
175        self.as_str()
176    }
177}
178
179impl Borrow<str> for RcStr {
180    fn borrow(&self) -> &str {
181        self.as_str()
182    }
183}
184
185impl From<BytesStr> for RcStr {
186    fn from(s: BytesStr) -> Self {
187        let bytes: Vec<u8> = s.into_bytes().into();
188        RcStr::from(unsafe {
189            // Safety: BytesStr are valid utf-8
190            String::from_utf8_unchecked(bytes)
191        })
192    }
193}
194
195impl From<Arc<String>> for RcStr {
196    fn from(s: Arc<String>) -> Self {
197        match Arc::try_unwrap(s) {
198            Ok(v) => new_atom(Cow::Owned(v)),
199            Err(arc) => new_atom(Cow::Borrowed(&**arc)),
200        }
201    }
202}
203
204impl From<String> for RcStr {
205    fn from(s: String) -> Self {
206        new_atom(Cow::Owned(s))
207    }
208}
209
210impl From<&'_ str> for RcStr {
211    fn from(s: &str) -> Self {
212        new_atom(Cow::Borrowed(s))
213    }
214}
215
216impl From<Cow<'_, str>> for RcStr {
217    fn from(s: Cow<str>) -> Self {
218        new_atom(s)
219    }
220}
221
222/// Mimic `&str`
223impl AsRef<Path> for RcStr {
224    fn as_ref(&self) -> &Path {
225        self.as_str().as_ref()
226    }
227}
228
229/// Mimic `&str`
230impl AsRef<OsStr> for RcStr {
231    fn as_ref(&self) -> &OsStr {
232        self.as_str().as_ref()
233    }
234}
235
236/// Mimic `&str`
237impl AsRef<[u8]> for RcStr {
238    fn as_ref(&self) -> &[u8] {
239        self.as_str().as_ref()
240    }
241}
242
243impl From<RcStr> for BytesStr {
244    fn from(value: RcStr) -> Self {
245        Self::from_str_slice(value.as_str())
246    }
247}
248
249impl PartialEq<str> for RcStr {
250    fn eq(&self, other: &str) -> bool {
251        self.as_str() == other
252    }
253}
254
255impl PartialEq<&'_ str> for RcStr {
256    fn eq(&self, other: &&str) -> bool {
257        self.as_str() == *other
258    }
259}
260
261impl PartialEq<String> for RcStr {
262    fn eq(&self, other: &String) -> bool {
263        self.as_str() == other.as_str()
264    }
265}
266
267impl Debug for RcStr {
268    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269        Debug::fmt(&self.as_str(), f)
270    }
271}
272
273impl Display for RcStr {
274    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275        Display::fmt(&self.as_str(), f)
276    }
277}
278
279impl From<RcStr> for String {
280    fn from(s: RcStr) -> Self {
281        s.into_owned()
282    }
283}
284
285impl From<RcStr> for PathBuf {
286    fn from(s: RcStr) -> Self {
287        String::from(s).into()
288    }
289}
290
291impl Clone for RcStr {
292    #[inline(always)]
293    fn clone(&self) -> Self {
294        let alias = self.unsafe_data;
295        // We only need to increment the ref count for DYNAMIC_TAG values
296        // For STATIC_TAG and INLINE_TAG we can just copy the value.
297        if alias.tag_byte() & TAG_MASK == DYNAMIC_TAG {
298            unsafe {
299                let arc = dynamic::restore_arc(alias);
300                forget(arc.clone());
301                forget(arc);
302            }
303        }
304
305        RcStr { unsafe_data: alias }
306    }
307}
308
309impl Default for RcStr {
310    fn default() -> Self {
311        rcstr!("")
312    }
313}
314
315impl PartialEq for RcStr {
316    fn eq(&self, other: &Self) -> bool {
317        // For inline RcStrs this is sufficient and for out of line values it handles a simple
318        // identity cases
319        if self.unsafe_data == other.unsafe_data {
320            return true;
321        }
322        // They can still be equal if they are both stored on the heap
323        match (self.location(), other.location()) {
324            (PREHASHED_STRING_LOCATION, PREHASHED_STRING_LOCATION) => {
325                let l = unsafe { deref_from(self.unsafe_data) };
326                let r = unsafe { deref_from(other.unsafe_data) };
327                l.hash == r.hash && l.value == r.value
328            }
329            // NOTE: it is never possible for an inline storage string to compare equal to a dynamic
330            // allocated string, the construction routines separate the strings based on length.
331            _ => false,
332        }
333    }
334}
335
336impl Eq for RcStr {}
337
338impl PartialOrd for RcStr {
339    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
340        Some(self.cmp(other))
341    }
342}
343
344impl Ord for RcStr {
345    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
346        self.as_str().cmp(other.as_str())
347    }
348}
349
350impl Hash for RcStr {
351    fn hash<H: Hasher>(&self, state: &mut H) {
352        match self.location() {
353            PREHASHED_STRING_LOCATION => {
354                let l = unsafe { deref_from(self.unsafe_data) };
355                state.write_u64(l.hash);
356                state.write_u8(0xff); // matches the implementation of the `str` Hash impl
357            }
358            INLINE_LOCATION => {
359                self.inline_as_str().hash(state);
360            }
361            _ => unsafe { debug_unreachable!() },
362        }
363    }
364}
365
366impl Serialize for RcStr {
367    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
368        serializer.serialize_str(self.as_str())
369    }
370}
371
372impl<'de> Deserialize<'de> for RcStr {
373    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
374        let s = String::deserialize(deserializer)?;
375        Ok(RcStr::from(s))
376    }
377}
378
379impl Encode for RcStr {
380    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
381        self.as_str().encode(encoder)
382    }
383}
384
385impl<Context> Decode<Context> for RcStr {
386    fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
387        Ok(RcStr::from(String::decode(decoder)?))
388    }
389}
390
391impl_borrow_decode!(RcStr);
392
393impl Drop for RcStr {
394    fn drop(&mut self) {
395        match self.tag() {
396            DYNAMIC_TAG => unsafe { drop(dynamic::restore_arc(self.unsafe_data)) },
397            STATIC_TAG => {
398                // do nothing, these are never deallocated
399            }
400            INLINE_TAG => {
401                // do nothing, these payloads need no drop logic
402            }
403            _ => unsafe { debug_unreachable!() },
404        }
405    }
406}
407
408// Exports for our macro
409#[doc(hidden)]
410pub const fn inline_atom(s: &str) -> Option<RcStr> {
411    dynamic::inline_atom(s)
412}
413
414#[doc(hidden)]
415#[inline(always)]
416pub fn from_static(s: &'static PrehashedString) -> RcStr {
417    dynamic::new_static_atom(s)
418}
419#[doc(hidden)]
420pub use dynamic::PrehashedString;
421
422#[doc(hidden)]
423pub const fn make_const_prehashed_string(text: &'static str) -> PrehashedString {
424    PrehashedString {
425        value: dynamic::Payload::Ref(text),
426        hash: hash_bytes(text.as_bytes()),
427    }
428}
429
430/// Create an rcstr from a string literal.
431/// allocates the RcStr inline when possible otherwise uses a `LazyLock` to manage the allocation.
432#[macro_export]
433macro_rules! rcstr {
434    ($s:expr) => {{
435        const INLINE: core::option::Option<$crate::RcStr> = $crate::inline_atom($s);
436        // This condition can be compile time evaluated and inlined.
437        if INLINE.is_some() {
438            INLINE.unwrap()
439        } else {
440            fn get_rcstr() -> $crate::RcStr {
441                // Allocate static storage for the PrehashedString
442                static RCSTR_STORAGE: $crate::PrehashedString =
443                    $crate::make_const_prehashed_string($s);
444                // This basically just tags a bit onto the raw pointer and wraps it in an RcStr
445                // should be fast enough to do every time.
446                $crate::from_static(&RCSTR_STORAGE)
447            }
448            get_rcstr()
449        }
450    }};
451}
452
453/// noop
454impl ShrinkToFit for RcStr {
455    #[inline(always)]
456    fn shrink_to_fit(&mut self) {}
457}
458
459#[cfg(all(feature = "napi", target_family = "wasm"))]
460compile_error!("The napi feature cannot be enabled for wasm targets");
461
462#[cfg(all(feature = "napi", not(target_family = "wasm")))]
463mod napi_impl {
464    use napi::{
465        bindgen_prelude::{FromNapiValue, ToNapiValue, TypeName, ValidateNapiValue},
466        sys::{napi_env, napi_value},
467    };
468
469    use super::*;
470
471    impl TypeName for RcStr {
472        fn type_name() -> &'static str {
473            String::type_name()
474        }
475
476        fn value_type() -> napi::ValueType {
477            String::value_type()
478        }
479    }
480
481    impl ToNapiValue for RcStr {
482        unsafe fn to_napi_value(env: napi_env, val: Self) -> napi::Result<napi_value> {
483            unsafe { ToNapiValue::to_napi_value(env, val.as_str()) }
484        }
485    }
486
487    impl FromNapiValue for RcStr {
488        unsafe fn from_napi_value(env: napi_env, napi_val: napi_value) -> napi::Result<Self> {
489            Ok(RcStr::from(unsafe {
490                String::from_napi_value(env, napi_val)
491            }?))
492        }
493    }
494
495    impl ValidateNapiValue for RcStr {
496        unsafe fn validate(env: napi_env, napi_val: napi_value) -> napi::Result<napi_value> {
497            unsafe { String::validate(env, napi_val) }
498        }
499    }
500}
501
502#[cfg(test)]
503mod tests {
504    use std::mem::ManuallyDrop;
505
506    use super::*;
507
508    #[test]
509    fn test_refcount() {
510        fn refcount(str: &RcStr) -> usize {
511            assert!(str.tag() == DYNAMIC_TAG);
512            let arc = ManuallyDrop::new(unsafe { dynamic::restore_arc(str.unsafe_data) });
513            triomphe::Arc::count(&arc)
514        }
515
516        let str = RcStr::from("this is a long string that won't be inlined");
517
518        assert_eq!(refcount(&str), 1);
519        assert_eq!(refcount(&str), 1); // refcount should not modify the refcount itself
520
521        let cloned_str = str.clone();
522        assert_eq!(refcount(&str), 2);
523
524        drop(cloned_str);
525        assert_eq!(refcount(&str), 1);
526
527        let _ = str.clone().into_owned();
528        assert_eq!(refcount(&str), 1);
529    }
530
531    #[test]
532    fn test_rcstr() {
533        // Test enough to exceed the small string optimization
534        assert_eq!(rcstr!(""), RcStr::default());
535        assert_eq!(rcstr!(""), RcStr::from(""));
536        assert_eq!(rcstr!("a"), RcStr::from("a"));
537        assert_eq!(rcstr!("ab"), RcStr::from("ab"));
538        assert_eq!(rcstr!("abc"), RcStr::from("abc"));
539        assert_eq!(rcstr!("abcd"), RcStr::from("abcd"));
540        assert_eq!(rcstr!("abcde"), RcStr::from("abcde"));
541        assert_eq!(rcstr!("abcdef"), RcStr::from("abcdef"));
542        assert_eq!(rcstr!("abcdefg"), RcStr::from("abcdefg"));
543        assert_eq!(rcstr!("abcdefgh"), RcStr::from("abcdefgh"));
544        assert_eq!(rcstr!("abcdefghi"), RcStr::from("abcdefghi"));
545    }
546
547    #[test]
548    fn test_static_atom() {
549        const LONG: &str = "a very long string that lives forever";
550        let leaked = rcstr!(LONG);
551        let not_leaked = RcStr::from(LONG);
552        assert_ne!(leaked.tag(), not_leaked.tag());
553        assert_eq!(leaked, not_leaked);
554    }
555
556    #[test]
557    fn test_inline_atom() {
558        // This is a silly test, just asserts that we can evaluate this in a constant context.
559        const STR: RcStr = {
560            let inline = inline_atom("hello");
561            if inline.is_some() {
562                inline.unwrap()
563            } else {
564                unreachable!();
565            }
566        };
567        assert_eq!(STR, RcStr::from("hello"));
568    }
569}