Skip to main content

stringtheory/
lib.rs

1//! Sharing-optimized strings and string interning utilities.
2//!
3//! `stringtheory` provides two main components: a sharing-optimized string type, `MetaString`, and string interning
4//! implementations (`FixedSizeInterner`, `GenericMapInterner`, etc). These components are meant to work in concert,
5//! allowing for using a single string type that can handle owned, shared, and interned strings, and providing a way to
6//! efficiently intern strings when possible.
7#![deny(warnings)]
8#![deny(missing_docs)]
9// The tag enum values are shifted into one byte of a `usize`, so their values are never truncated on supported
10// platforms.
11#![allow(clippy::enum_clike_unportable_variant)]
12
13use std::{
14    borrow::{Borrow, Cow},
15    fmt, hash,
16    mem::ManuallyDrop,
17    ops::Deref,
18    ptr::NonNull,
19    slice::from_raw_parts,
20    str::from_utf8_unchecked,
21    sync::Arc,
22};
23
24use serde::{Deserialize, Serialize};
25
26mod clone;
27
28pub use self::clone::CheapMetaString;
29
30pub mod interning;
31use self::interning::{InternedString, InternedStringState, Interner};
32
33const ZERO_VALUE: usize = 0;
34const TOP_MOST_BIT: usize = usize::MAX & !(isize::MAX as usize);
35const INLINED_STR_DATA_BUF_LEN: usize = std::mem::size_of::<usize>() * 3;
36// MetaString stores its discriminant in the top byte of the third machine word, which lands at a different byte
37// offset in memory depending on endianness.
38const TOP_BYTE_INDEX: usize = if cfg!(target_endian = "little") {
39    std::mem::size_of::<usize>() - 1
40} else {
41    0
42};
43const INLINED_STR_TAG_INDEX: usize = std::mem::size_of::<usize>() * 2 + TOP_BYTE_INDEX;
44const INLINED_STR_MAX_LEN: usize = INLINED_STR_TAG_INDEX;
45const INLINED_STR_MAX_LEN_U8: u8 = INLINED_STR_MAX_LEN as u8;
46
47const UNION_TYPE_TAG_VALUE_STATIC: u8 = get_offset_tag_value(0);
48const UNION_TYPE_TAG_VALUE_INTERNED_FIXED_SIZE: u8 = get_offset_tag_value(1);
49const UNION_TYPE_TAG_VALUE_INTERNED_GENERIC_MAP: u8 = get_offset_tag_value(2);
50const UNION_TYPE_TAG_VALUE_SHARED: u8 = get_offset_tag_value(3);
51
52const fn get_offset_tag_value(tag: u8) -> u8 {
53    const UNION_TYPE_TAG_VALUE_BASE: u8 = INLINED_STR_MAX_LEN as u8 + 1;
54
55    if tag > (u8::MAX - INLINED_STR_MAX_LEN as u8) {
56        panic!("Union type tag value must fit in the discriminant byte.");
57    }
58
59    tag + UNION_TYPE_TAG_VALUE_BASE
60}
61
62const fn get_scaled_union_tag(tag: u8) -> usize {
63    // We want to shift our tag value (single byte) to make it the top most byte in a `usize`.
64    const UNION_TYPE_TAG_VALUE_SHIFT: u32 = (std::mem::size_of::<usize>() as u32 - 1) * 8;
65
66    (tag as usize) << UNION_TYPE_TAG_VALUE_SHIFT
67}
68
69// High-level invariant checks to ensure `stringtheory` isn't being used on an unsupported platform.
70#[cfg(not(target_pointer_width = "64"))]
71const _INVARIANTS_CHECK: () = {
72    compile_error!("`stringtheory` is only supported on 64-bit platforms.");
73};
74
75const fn is_tagged(cap: u8) -> bool {
76    cap & 0b10000000 != 0
77}
78
79const fn tag_cap(cap: usize) -> usize {
80    cap | TOP_MOST_BIT
81}
82
83const fn untag_cap(cap: usize) -> usize {
84    cap & !(TOP_MOST_BIT)
85}
86
87#[derive(Clone, Copy, Eq, PartialEq)]
88#[repr(usize)]
89enum Zero {
90    Zero = ZERO_VALUE,
91}
92
93#[derive(Clone, Copy, Debug, Eq, PartialEq)]
94#[repr(usize)]
95enum Tag {
96    Static = get_scaled_union_tag(UNION_TYPE_TAG_VALUE_STATIC),
97    InternedFixedSize = get_scaled_union_tag(UNION_TYPE_TAG_VALUE_INTERNED_FIXED_SIZE),
98    InternedGenericMap = get_scaled_union_tag(UNION_TYPE_TAG_VALUE_INTERNED_GENERIC_MAP),
99    Shared = get_scaled_union_tag(UNION_TYPE_TAG_VALUE_SHARED),
100}
101
102#[repr(C)]
103#[derive(Clone, Copy)]
104struct EmptyUnion {
105    ptr: Zero, // Field one.
106    len: Zero, // Field two.
107    cap: Zero, // Field three.
108}
109
110impl EmptyUnion {
111    const fn new() -> Self {
112        Self {
113            ptr: Zero::Zero,
114            len: Zero::Zero,
115            cap: Zero::Zero,
116        }
117    }
118}
119
120#[repr(C)]
121#[derive(Clone, Copy)]
122struct OwnedUnion {
123    ptr: *mut u8, // Field one
124    len: usize,   // Field two.
125    cap: usize,   // Field three.
126}
127
128impl OwnedUnion {
129    #[inline]
130    fn as_str(&self) -> &str {
131        // SAFETY: We know our pointer is valid, and non-null, since it's derived from a valid `String`, and that the
132        // data it points to is valid UTF-8, again, by virtue of it being derived from a valid `String`.
133        unsafe { from_utf8_unchecked(from_raw_parts(self.ptr, self.len)) }
134    }
135
136    fn into_owned(self) -> String {
137        // SAFETY: We know our pointer is valid, and non-null, since it's derived from a valid `String`, and that the
138        // data it points to is valid UTF-8, again, by virtue of it being derived from a valid `String`.
139        unsafe { String::from_raw_parts(self.ptr, self.len, untag_cap(self.cap)) }
140    }
141}
142
143#[repr(C)]
144#[derive(Clone, Copy)]
145struct StaticUnion {
146    value: &'static str, // Fields one and two.
147    _cap: Tag,           // Field three.
148}
149
150impl StaticUnion {
151    #[inline]
152    const fn as_str(&self) -> &str {
153        self.value
154    }
155}
156
157#[repr(C)]
158struct InternedUnion {
159    state: InternedStateUnion, // Fields one and two.
160    _cap: Tag,                 // Field three.
161}
162
163impl Drop for InternedUnion {
164    fn drop(&mut self) {
165        match self._cap {
166            Tag::InternedFixedSize => {
167                let state = unsafe { ManuallyDrop::take(&mut self.state.fixed_size) };
168                drop(state);
169            }
170            Tag::InternedGenericMap => {
171                let state = unsafe { ManuallyDrop::take(&mut self.state.generic_map) };
172                drop(state);
173            }
174            _ => unreachable!(),
175        }
176    }
177}
178
179impl Clone for InternedUnion {
180    fn clone(&self) -> Self {
181        // SAFETY: We use our tag (stored in `_cap`) to determine which field to access and clone, which
182        // ensures we only access fields which are initialized.
183        let state = unsafe {
184            match self._cap {
185                Tag::InternedFixedSize => InternedStateUnion {
186                    fixed_size: self.state.fixed_size.clone(),
187                },
188                Tag::InternedGenericMap => InternedStateUnion {
189                    generic_map: self.state.generic_map.clone(),
190                },
191                _ => unreachable!(),
192            }
193        };
194
195        Self { state, _cap: self._cap }
196    }
197}
198
199#[repr(C)]
200union InternedStateUnion {
201    fixed_size: ManuallyDrop<self::interning::fixed_size::StringState>,
202    generic_map: ManuallyDrop<self::interning::map::StringState>,
203}
204
205#[repr(C)]
206struct SharedUnion {
207    ptr: NonNull<str>, // Fields one and two
208    _cap: Tag,         // Field three.
209}
210
211impl SharedUnion {
212    #[inline]
213    const fn as_str(&self) -> &str {
214        // SAFETY: The pointee is still live by virtue of being held in an `Arc`.
215        unsafe { self.ptr.as_ref() }
216    }
217}
218
219#[repr(C)]
220#[derive(Clone, Copy)]
221struct InlinedUnion {
222    // Data is arranged as contiguous string data followed by the endian-specific length/discriminant byte.
223    data: [u8; INLINED_STR_DATA_BUF_LEN], // Fields one, two, and three.
224}
225
226impl InlinedUnion {
227    #[inline]
228    fn as_str(&self) -> &str {
229        let len = self.data[INLINED_STR_MAX_LEN] as usize;
230
231        // SAFETY: We know our data is valid UTF-8 since we only ever derive inlined strings from a valid string
232        // reference.
233        unsafe { from_utf8_unchecked(&self.data[0..len]) }
234    }
235}
236
237#[repr(C)]
238#[derive(Clone, Copy)]
239struct DiscriminantUnion {
240    // Fields one, two, and three. The active discriminant byte is selected by `INLINED_STR_TAG_INDEX`.
241    data: [u8; INLINED_STR_DATA_BUF_LEN],
242}
243
244#[derive(Debug, Eq, PartialEq)]
245enum UnionType {
246    Empty,
247    Owned,
248    Static,
249    InternedFixedSize,
250    InternedGenericMap,
251    Inlined,
252    Shared,
253}
254
255impl UnionType {
256    #[inline]
257    const fn is_owned(&self) -> bool {
258        matches!(self, UnionType::Owned)
259    }
260}
261
262impl DiscriminantUnion {
263    #[inline]
264    const fn get_union_type(&self) -> UnionType {
265        // At a high level, we encode the type of the union into one byte of the struct, which overlaps with the
266        // high byte of the third machine word: the capacity of owned strings, the length of an inlined string,
267        // and the unused/tag field of other string types.
268        //
269        // Our logic is simple here:
270        //
271        // - Allocations can only ever be as large as `isize::MAX`, which means that the top-most bit of the capacity
272        //   value would never be used for a valid allocation.
273        // - In turn, the length of a string can also only ever be as large as `isize::MAX`, which means that the
274        //   top-most bit of the length byte for any string type would never be used
275        // - Inlined strings can only ever be as long as the endian-specific inline capacity, which means that the
276        //   top-most bit of the length byte for an inlined string would never be used.
277        // - Static strings and interned strings only occupy the first two fields, which means their capacity should not
278        //   be used.
279        //
280        // As such, we encode the possible string types as follows:
281        //
282        // - when all fields are zero, we have an empty string
283        // - when the tag byte has the top bit set, we have an owned string
284        // - when the tag byte does _not_ have the top bit set, and the value is less than or equal to the inline
285        //   capacity, we have an inlined string
286        // - when the tag byte does _not_ have the top bit set, and the value is greater than the inline capacity, we
287        //   interpret the specific value of the tag byte as a discriminant for the remaining string types (static,
288        //   interned, etc)
289        //
290        // The tag byte is the byte where the upper-most bits of the third machine word are stored. This overlaps the
291        // high byte of an owned string's capacity, the length byte of an inlined string, and the unused/tag field of
292        // static, interned, and shared strings. The actual byte index differs by endianness: little-endian uses the
293        // last byte of the layout, while big-endian uses the first byte of the third machine word.
294        //
295        // The little-endian layout for an inlined string and an owned string looks like this:
296        //
297        //                ~ an inlined string, "hello, world", with a length of 12 (0C) ~
298        //      ┌───────────────────────────────────────────────────────────────────────────────┐
299        //      │ 68 65 6C 6C 6F 20 77 6F    72 6C 64 21 ?? ?? ?? ??    ?? ?? ?? ?? ?? ?? ?? 0C │
300        //      └───────────────────────────────────────────────────────────────────────────────┘
301        //                                                                                    ▲
302        //                                                                                    ├──── tag byte
303        //                          ~ an owned string with a capacity of 64 ~                 ▼
304        //      ┌─────────────────────────┐┌─────────────────────────┐┌─────────────────────────┐
305        //      │ ?? ?? ?? ?? ?? ?? ?? ?? ││ ?? ?? ?? ?? ?? ?? ?? ?? ││ 40 00 00 00 00 00 00 80 │
306        //      └─────────────────────────┘└─────────────────────────┘└─────────────────────────┘
307        //                                                                                    ▲
308        //                 original capacity: 64                  (0x0000000000000040)        │
309        //                 "tagged" capacity: 9223372036854775872 (0x8000000000000040)        │
310        //                                                           ▲                        │
311        //                     (tag bit) ────────────────────────────┘                        │
312        //                                                                                    │
313        //                       inlined tag byte (0x0C)  [0 0 0 0 1 1 0 0] ◀────────────────┤
314        //                       owned tag byte (0x80)    [1 0 0 0 0 0 0 0] ◀────────────────┤
315        //                                                                                    │
316        //                       maximum little-endian inline length                           │
317        //                       23 (0x17)                [0 0 0 1 0 1 1 1] ◀────────────────┤
318        //                                                                                    │
319        //                       "owned" discriminant                                         │
320        //                       bitmask (any X bit)       [X X X ? ? ? ? ?] ◀────────────────┘
321        //
322        // Given that we know an inlined string cannot be any longer than the inline capacity, we know that the
323        // top-most bit in the tag byte can never be set, as it would imply a length of _at least_ 128. With that, we
324        // utilize invariant #3 of `Inner` -- allocations can never be larger than `isize::MAX` -- which lets us
325        // safely "tag" an owned string's capacity -- setting the upper most bit to 1 -- to indicate that it's an
326        // owned string.
327
328        // If the top bit is set, we know we're dealing with an owned string.
329        let tag_byte = self.data[INLINED_STR_TAG_INDEX];
330
331        if is_tagged(tag_byte) {
332            return UnionType::Owned;
333        }
334
335        // The top-most bit has to be set for an owned string, but isn't set for any other type, so try differentiating
336        // at this point.
337        match tag_byte {
338            // Empty string. Easy.
339            0 => UnionType::Empty,
340
341            // Anything between 1 and INLINED_STR_MAX_LEN, inclusive, is an inlined string.
342            1..=INLINED_STR_MAX_LEN_U8 => UnionType::Inlined,
343
344            // These are fixed values above the inline capacity and below the owned-string tag bit, so we just match
345            // them directly.
346            UNION_TYPE_TAG_VALUE_STATIC => UnionType::Static,
347            UNION_TYPE_TAG_VALUE_INTERNED_FIXED_SIZE => UnionType::InternedFixedSize,
348            UNION_TYPE_TAG_VALUE_INTERNED_GENERIC_MAP => UnionType::InternedGenericMap,
349            UNION_TYPE_TAG_VALUE_SHARED => UnionType::Shared,
350
351            // If we haven't matched any specific type tag value, then this is something else that we don't handle or
352            // know about... which we handle as just acting like we're an empty string for simplicity.
353            _ => UnionType::Empty,
354        }
355    }
356}
357
358/// The core data structure for holding all different string variants.
359///
360/// This union has six data fields -- one for each possible string variant -- and a discriminant field, used to
361/// determine which string variant is actually present. The discriminant field interrogates the bits in each machine
362/// word field (all variants are three machine words) to determine which bit patterns are valid or not for a given
363/// variant, allowing the string variant to be authoritatively determined.
364///
365/// # Invariants
366///
367/// This code depends on a number of invariants in order to work correctly:
368///
369/// 1. Only used on 64-bit little- or big-endian platforms. (checked at compile-time via _INVARIANTS_CHECK)
370/// 2. The data pointers for `String` and `&'static str` can't ever be null when the strings are non-empty.
371/// 3. Allocations can never be larger than `isize::MAX` (see [here][rust_isize_alloc_limit]), meaning that any
372///    length/capacity field for a string can't ever be larger than `isize::MAX`, implying the highest bit for
373///    length/capacity should always be 0.
374/// 4. An inlined string can only hold bytes before the endian-specific tag byte, meaning that the length byte for that
375///    string can never exceed the inline capacity. (_We_ have to provide this invariant, which is handled in
376///    `Inner::try_inlined`.)
377///
378/// [rust_isize_alloc_limit]: https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.from_size_align
379union Inner {
380    empty: EmptyUnion,
381    owned: OwnedUnion,
382    static_: StaticUnion,
383    interned: ManuallyDrop<InternedUnion>,
384    shared: ManuallyDrop<SharedUnion>,
385    inlined: InlinedUnion,
386    discriminant: DiscriminantUnion,
387}
388
389impl Inner {
390    const fn empty() -> Self {
391        Self {
392            empty: EmptyUnion::new(),
393        }
394    }
395
396    fn owned(value: String) -> Self {
397        match value.capacity() {
398            // The string we got is empty.
399            0 => Self::empty(),
400            cap => {
401                let mut value = value.into_bytes();
402
403                let ptr = value.as_mut_ptr();
404                let len = value.len();
405
406                // We're taking ownership of the underlying string allocation so we can't let it drop.
407                std::mem::forget(value);
408
409                Self {
410                    owned: OwnedUnion {
411                        ptr,
412                        len,
413                        cap: tag_cap(cap),
414                    },
415                }
416            }
417        }
418    }
419
420    const fn static_str(value: &'static str) -> Self {
421        match value.len() {
422            0 => Self::empty(),
423            _ => Self {
424                static_: StaticUnion {
425                    value,
426                    _cap: Tag::Static,
427                },
428            },
429        }
430    }
431
432    fn interned(value: InternedString) -> Self {
433        match value.len() {
434            0 => Self::empty(),
435            _len => {
436                let (state, tag) = match value.into_state() {
437                    InternedStringState::FixedSize(fixed_size) => (
438                        InternedStateUnion {
439                            fixed_size: ManuallyDrop::new(fixed_size),
440                        },
441                        Tag::InternedFixedSize,
442                    ),
443                    InternedStringState::GenericMap(generic_map) => (
444                        InternedStateUnion {
445                            generic_map: ManuallyDrop::new(generic_map),
446                        },
447                        Tag::InternedGenericMap,
448                    ),
449                };
450
451                Self {
452                    interned: ManuallyDrop::new(InternedUnion { state, _cap: tag }),
453                }
454            }
455        }
456    }
457
458    fn shared(value: Arc<str>) -> Self {
459        match value.len() {
460            0 => Self::empty(),
461            _len => Self {
462                shared: ManuallyDrop::new(SharedUnion {
463                    // SAFETY: We know `ptr` is non-null because `Arc::into_raw` is called on a valid `Arc<str>`.
464                    ptr: unsafe { NonNull::new_unchecked(Arc::into_raw(value).cast_mut()) },
465                    _cap: Tag::Shared,
466                }),
467            },
468        }
469    }
470
471    fn try_inlined(value: &str) -> Option<Self> {
472        match value.len() {
473            0 => Some(Self::empty()),
474            len => {
475                if len > INLINED_STR_MAX_LEN {
476                    return None;
477                }
478
479                let mut data = [0; INLINED_STR_DATA_BUF_LEN];
480
481                // SAFETY: We know it fits because we just checked that the string length is within the inline capacity.
482                data[INLINED_STR_MAX_LEN] = len as u8;
483
484                let buf = value.as_bytes();
485                data[0..len].copy_from_slice(buf);
486
487                Some(Self {
488                    inlined: InlinedUnion { data },
489                })
490            }
491        }
492    }
493
494    #[inline]
495    fn as_str(&self) -> &str {
496        let union_type = unsafe { self.discriminant.get_union_type() };
497        match union_type {
498            UnionType::Empty => "",
499            UnionType::Owned => {
500                let owned = unsafe { &self.owned };
501                owned.as_str()
502            }
503            UnionType::Static => {
504                let static_ = unsafe { &self.static_ };
505                static_.as_str()
506            }
507            UnionType::InternedFixedSize => {
508                let interned = unsafe { &self.interned.state.fixed_size };
509                interned.as_str()
510            }
511            UnionType::InternedGenericMap => {
512                let interned = unsafe { &self.interned.state.generic_map };
513                interned.as_str()
514            }
515            UnionType::Shared => {
516                let shared = unsafe { &self.shared };
517                shared.as_str()
518            }
519            UnionType::Inlined => {
520                let inlined = unsafe { &self.inlined };
521                inlined.as_str()
522            }
523        }
524    }
525
526    #[inline]
527    const fn get_union_type(&self) -> UnionType {
528        unsafe { self.discriminant.get_union_type() }
529    }
530
531    fn into_owned(mut self) -> String {
532        let union_type = unsafe { self.discriminant.get_union_type() };
533        match union_type {
534            UnionType::Empty => String::new(),
535            UnionType::Owned => {
536                // We're (`Inner`) being consumed here, but we need to update our internal state to ensure that our drop
537                // logic doesn't try to double free the string allocation.
538                let owned = unsafe { self.owned };
539                self.empty = EmptyUnion::new();
540
541                owned.into_owned()
542            }
543            UnionType::Static => {
544                let static_ = unsafe { self.static_ };
545                static_.as_str().to_owned()
546            }
547            UnionType::InternedFixedSize => {
548                let interned = unsafe { &self.interned.state.fixed_size };
549                interned.as_str().to_owned()
550            }
551            UnionType::InternedGenericMap => {
552                let interned = unsafe { &self.interned.state.generic_map };
553                interned.as_str().to_owned()
554            }
555            UnionType::Shared => {
556                let shared = unsafe { &self.shared };
557                shared.as_str().to_owned()
558            }
559            UnionType::Inlined => {
560                let inlined = unsafe { self.inlined };
561                inlined.as_str().to_owned()
562            }
563        }
564    }
565}
566
567impl Drop for Inner {
568    fn drop(&mut self) {
569        let union_type = unsafe { self.discriminant.get_union_type() };
570        match union_type {
571            UnionType::Owned => {
572                let owned = unsafe { &mut self.owned };
573
574                let ptr = owned.ptr;
575                let len = owned.len;
576                let cap = untag_cap(owned.cap);
577
578                // SAFETY: The pointer has to be non-null, because we only ever construct an owned variant when the
579                // `String` has a non-zero capacity, which implies a valid allocation, and thus a valid, non-null
580                // pointer.
581                let data = unsafe { Vec::<u8>::from_raw_parts(ptr, len, cap) };
582                drop(data);
583            }
584            UnionType::InternedFixedSize | UnionType::InternedGenericMap => {
585                let interned = unsafe { &mut self.interned };
586
587                // SAFETY: We're already dropping `Inner`, so nothing else can use the `InternedString` value after we
588                // consume it here.
589                let data = unsafe { ManuallyDrop::take(interned) };
590                drop(data);
591            }
592            UnionType::Shared => {
593                let shared = unsafe { &mut self.shared };
594
595                // Decrement the strong count before we drop, ensuring the `Arc` has a chance to clean itself up if this
596                // is the less strong reference.
597                //
598                // SAFETY: We know `shared.ptr` was obtained from `Arc::into_raw`, so it's valid to decrement on. We
599                // also know the backing storage is still live because it has to be by virtue of us being here.
600                unsafe {
601                    Arc::decrement_strong_count(shared.ptr.as_ptr().cast_const());
602                }
603            }
604            _ => {}
605        }
606    }
607}
608
609impl Clone for Inner {
610    fn clone(&self) -> Self {
611        let union_type = unsafe { self.discriminant.get_union_type() };
612        match union_type {
613            UnionType::Empty => Self::empty(),
614            UnionType::Owned => {
615                let owned = unsafe { self.owned };
616                let s = owned.as_str();
617
618                // We specifically try to inline here.
619                //
620                // At a high-level, when we're _given_ an owned string, we avoid inlining because we don't want to trash
621                // the underlying allocation since we may be asked to give it back later (via `MetaString::into_owned`).
622                // However, when we're _cloning_, we'd rather avoiding allocating if we can help it.
623                Self::try_inlined(s).unwrap_or_else(|| Self::owned(s.to_owned()))
624            }
625            UnionType::Static => Self {
626                static_: unsafe { self.static_ },
627            },
628            UnionType::InternedFixedSize | UnionType::InternedGenericMap => Self {
629                interned: unsafe { self.interned.clone() },
630            },
631            UnionType::Shared => {
632                let shared = unsafe { &self.shared };
633
634                // We have to increment the strong count before cloning.
635                //
636                // SAFETY: We know `shared.ptr` was obtained from `Arc::into_raw`. We also know that if we're cloning
637                // this value, that the underlying `Arc` must still be live, since we're holding a reference to it.
638                unsafe {
639                    Arc::increment_strong_count(shared.ptr.as_ptr().cast_const());
640                }
641
642                Self {
643                    shared: ManuallyDrop::new(SharedUnion {
644                        ptr: shared.ptr,
645                        _cap: Tag::Shared,
646                    }),
647                }
648            }
649            UnionType::Inlined => Self {
650                inlined: unsafe { self.inlined },
651            },
652        }
653    }
654}
655
656// SAFETY: None of our union variants are tied to the original thread they were created on.
657unsafe impl Send for Inner {}
658
659// SAFETY: None of our union variants use any form of interior mutability and are thus safe to be shared between
660// threads.
661unsafe impl Sync for Inner {}
662
663/// An immutable string type that abstracts over various forms of string storage.
664///
665/// Normally, developers will work with either `String` (owned) or `&str` (borrowed) when dealing with strings. In some
666/// cases, though, it can be useful to work with strings that use alternative storage, such as those that are atomically
667/// shared (for example, `InternedString`). While using those string types themselves isn't complex, using them and
668/// _also_ supporting normal string types can be complex.
669///
670/// `MetaString` is an opinionated string type that abstracts over the normal string types like `String` and `&str`
671/// while also supporting alternative storage, such as interned strings from `FixedSizeInterner`, unifying these
672/// different variants behind a single concrete type.
673///
674/// ## Supported types
675///
676/// `MetaString` supports the following "variants":
677///
678/// - owned (`String` and non-inlineable `&str`)
679/// - static (`&'static str`)
680/// - interned (`InternedString`)
681/// - shared (`Arc<str>`)
682/// - inlined (up to 23 bytes on little-endian platforms, and up to 16 bytes on big-endian platforms)
683///
684/// ### Owned and borrowed strings
685///
686/// `MetaString` can be created from `String` and `&str` directly. For owned scenarios (`String`), the string value is
687/// simply wrapped. For borrowed strings, we attempt to inline them (see more below) or, if they can't be inlined, they
688/// are copied into a new `String`.
689///
690/// ### Static strings
691///
692/// `MetaString` can be created from `&'static str` directly. This is useful for string literals and other static
693/// strings that are too large to be inlined.
694///
695/// ### Interned strings
696///
697/// `MetaString` can also be created from `InternedString`, which is a string that has been interned (using an interner
698/// like [`FixedSizeInterner`][crate::interning::FixedSizeInterner] or
699/// [`GenericMapInterner`][crate::interning::GenericMapInterner]). Interned strings are essentially a combination of the
700/// properties of `Arc<T>` -- owned wrappers around an atomically reference counted piece of data -- and a fixed-size
701/// buffer, where we allocate one large buffer, and write many small strings into it, and provide references to those
702/// strings through `InternedString`.
703///
704/// ### Shared strings
705///
706/// `MetaString` can be created from `Arc<str>`, which is a string slice that can be atomically shared between threads.
707/// This is a simpler version of interned strings where strict memory control and re-use isn't required.
708///
709/// ### Inlined strings
710///
711/// Finally, `MetaString` can also be created by inlining small strings into `MetaString` itself, avoiding the need for
712/// any backing allocation. "Small string optimization" is a common optimization for string types where small strings
713/// can be stored directly in a string type itself by utilizing a "union"-style layout.
714///
715/// As `MetaString` utilizes such a layout, we can provide a small string optimization that allows for strings up to 23
716/// bytes in length on little-endian platforms, and up to 16 bytes in length on big-endian platforms.
717///
718/// ## Conversion methods
719///
720/// Implementations of `From<T>` exist for all of the aforementioned types to allow for easily converting to
721/// `MetaString`. Once a caller has a `MetaString` value, they're generally expected to interact with the string in a
722/// read-only way, as `MetaString` can be dereferenced directly to `&str`.
723///
724/// If a caller needs to be able to modify the string data, they can call `into_owned` to get an owned version of the
725/// string, make their modifications to the owned version, and then convert that back to `MetaString`.
726#[derive(Clone)]
727pub struct MetaString {
728    inner: Inner,
729}
730
731impl MetaString {
732    /// Creates an empty `MetaString`.
733    ///
734    /// This doesn't allocate.
735    pub const fn empty() -> Self {
736        Self { inner: Inner::empty() }
737    }
738
739    /// Creates a new `MetaString` from the given static string.
740    ///
741    /// This doesn't allocate.
742    pub const fn from_static(s: &'static str) -> Self {
743        Self {
744            inner: Inner::static_str(s),
745        }
746    }
747
748    /// Attempts to create a new `MetaString` from the given string if it can be inlined.
749    pub fn try_inline(s: &str) -> Option<Self> {
750        Inner::try_inlined(s).map(|inner| Self { inner })
751    }
752
753    /// Creates a new `MetaString` from the given string, using the provided interner.
754    ///
755    /// The string is inlined if possible. If it can't be inlined, the interner is tried. If interning fails, an owned
756    /// string is allocated.
757    pub fn from_interner<I>(s: &str, interner: &I) -> Self
758    where
759        I: Interner,
760    {
761        if let Some(inlined) = Self::try_inline(s) {
762            return inlined;
763        }
764        if let Some(interned) = interner.try_intern(s) {
765            return Self::from(interned);
766        }
767        Self::from(s.to_owned())
768    }
769
770    /// Returns `true` if `self` has a length of zero bytes.
771    pub fn is_empty(&self) -> bool {
772        self.deref().is_empty()
773    }
774
775    /// Returns `true` if `self` can be cheaply cloned.
776    pub const fn is_cheaply_cloneable(&self) -> bool {
777        // If we're wrapping an owned string, cloning means cloning that allocation. All other types are cheap to clone.
778        !self.inner.get_union_type().is_owned()
779    }
780
781    /// Consumes `self` and returns an owned `String`.
782    ///
783    /// If the `MetaString` is already owned, this will simply return the inner `String` directly. Otherwise, this will
784    /// allocate an owned version (`String`) of the string data.
785    pub fn into_owned(self) -> String {
786        self.inner.into_owned()
787    }
788}
789
790#[cfg(feature = "trace-model")]
791impl libdd_trace_model::TraceText for MetaString {
792    fn from_static(s: &'static str) -> Self {
793        MetaString::from_static(s)
794    }
795}
796
797impl Default for MetaString {
798    fn default() -> Self {
799        Self::empty()
800    }
801}
802
803impl hash::Hash for MetaString {
804    fn hash<H: hash::Hasher>(&self, state: &mut H) {
805        self.deref().hash(state)
806    }
807}
808
809impl PartialEq<str> for MetaString {
810    fn eq(&self, other: &str) -> bool {
811        self.deref() == other
812    }
813}
814
815impl PartialEq<&str> for MetaString {
816    fn eq(&self, other: &&str) -> bool {
817        self.deref() == *other
818    }
819}
820
821impl PartialEq<MetaString> for MetaString {
822    fn eq(&self, other: &MetaString) -> bool {
823        self.deref() == other.deref()
824    }
825}
826
827impl Eq for MetaString {}
828
829impl PartialOrd for MetaString {
830    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
831        Some(self.cmp(other))
832    }
833}
834
835impl Ord for MetaString {
836    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
837        self.deref().cmp(other.deref())
838    }
839}
840
841impl Borrow<str> for MetaString {
842    fn borrow(&self) -> &str {
843        self.deref()
844    }
845}
846
847impl Serialize for MetaString {
848    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
849    where
850        S: serde::Serializer,
851    {
852        serializer.serialize_str(self.deref())
853    }
854}
855
856impl<'de> Deserialize<'de> for MetaString {
857    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
858    where
859        D: serde::Deserializer<'de>,
860    {
861        struct MetaStringVisitor;
862
863        impl<'de> serde::de::Visitor<'de> for MetaStringVisitor {
864            type Value = MetaString;
865
866            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
867                formatter.write_str("a string")
868            }
869
870            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
871            where
872                E: serde::de::Error,
873            {
874                Ok(MetaString::from(v))
875            }
876        }
877
878        deserializer.deserialize_str(MetaStringVisitor)
879    }
880}
881
882impl From<String> for MetaString {
883    fn from(s: String) -> Self {
884        Self { inner: Inner::owned(s) }
885    }
886}
887
888impl From<&str> for MetaString {
889    fn from(s: &str) -> Self {
890        Self::try_inline(s).unwrap_or_else(|| Self::from(s.to_owned()))
891    }
892}
893
894impl From<Cow<'_, str>> for MetaString {
895    /// Converts a borrowed string as [`From<&str>`] does, inlining it when it's short enough, and keeps an owned string
896    /// without copying it.
897    fn from(s: Cow<'_, str>) -> Self {
898        match s {
899            Cow::Borrowed(s) => Self::from(s),
900            Cow::Owned(s) => Self::from(s),
901        }
902    }
903}
904
905impl From<InternedString> for MetaString {
906    fn from(s: InternedString) -> Self {
907        Self {
908            inner: Inner::interned(s),
909        }
910    }
911}
912
913impl From<Arc<str>> for MetaString {
914    fn from(s: Arc<str>) -> Self {
915        Self {
916            inner: Inner::shared(s),
917        }
918    }
919}
920
921impl From<MetaString> for protobuf::Chars {
922    fn from(value: MetaString) -> Self {
923        value.into_owned().into()
924    }
925}
926
927impl<'a> From<&'a MetaString> for protobuf::Chars {
928    fn from(value: &'a MetaString) -> Self {
929        // TODO: We're foregoing additional code/complexity to recover a static reference, when our string storage is
930        // static, in order to optimize the conversion to `Bytes` and then `Chars`.
931        //
932        // Static strings being written to Protocol Buffers should be decently rare across the codebase, so no biggie
933        // for now.
934        value.deref().into()
935    }
936}
937
938impl Deref for MetaString {
939    type Target = str;
940
941    fn deref(&self) -> &str {
942        self.inner.as_str()
943    }
944}
945
946impl AsRef<str> for MetaString {
947    fn as_ref(&self) -> &str {
948        self.deref()
949    }
950}
951
952impl fmt::Debug for MetaString {
953    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
954        self.deref().fmt(f)
955    }
956}
957
958impl fmt::Display for MetaString {
959    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
960        self.deref().fmt(f)
961    }
962}
963
964#[cfg(test)]
965mod tests {
966    use std::{borrow::Cow, num::NonZeroUsize, sync::Arc};
967
968    use proptest::{prelude::*, proptest};
969
970    use super::{
971        interning::GenericMapInterner, CheapMetaString, InlinedUnion, Inner, MetaString, UnionType,
972        INLINED_STR_MAX_LEN, INLINED_STR_TAG_INDEX, UNION_TYPE_TAG_VALUE_INTERNED_FIXED_SIZE,
973        UNION_TYPE_TAG_VALUE_INTERNED_GENERIC_MAP, UNION_TYPE_TAG_VALUE_SHARED, UNION_TYPE_TAG_VALUE_STATIC,
974    };
975    use crate::interning::{FixedSizeInterner, Interner as _};
976
977    fn discriminant_byte(inner: &Inner) -> u8 {
978        unsafe { inner.discriminant.data[INLINED_STR_TAG_INDEX] }
979    }
980
981    #[test]
982    fn struct_sizes() {
983        // Overall, we expect `MetaString`, and thus `Inner`, to always be three machine words.
984        assert_eq!(std::mem::size_of::<MetaString>(), std::mem::size_of::<usize>() * 3);
985        assert_eq!(std::mem::size_of::<Inner>(), std::mem::size_of::<usize>() * 3);
986
987        // We also expect all of inlined union variant to be the exact size of `Inner`, which means we're properly
988        // maximizing the available space for inlining.
989        assert_eq!(std::mem::size_of::<InlinedUnion>(), std::mem::size_of::<Inner>());
990    }
991
992    #[test]
993    fn inline_capacity_matches_target_endianness() {
994        let expected_inline_capacity = if cfg!(target_endian = "little") { 23 } else { 16 };
995
996        assert_eq!(INLINED_STR_MAX_LEN, expected_inline_capacity);
997    }
998
999    #[test]
1000    fn discriminant_byte_tracks_endian_specific_variant_tags() {
1001        let owned = MetaString::from(String::from("owned-value"));
1002        assert_eq!(owned.inner.get_union_type(), UnionType::Owned);
1003        assert!(discriminant_byte(&owned.inner) & 0b1000_0000 != 0);
1004
1005        let static_value = MetaString::from_static("static-value");
1006        assert_eq!(static_value.inner.get_union_type(), UnionType::Static);
1007        assert_eq!(discriminant_byte(&static_value.inner), UNION_TYPE_TAG_VALUE_STATIC);
1008
1009        let shared = MetaString::from(Arc::<str>::from("shared-value"));
1010        assert_eq!(shared.inner.get_union_type(), UnionType::Shared);
1011        assert_eq!(discriminant_byte(&shared.inner), UNION_TYPE_TAG_VALUE_SHARED);
1012
1013        let fixed_size_interner = FixedSizeInterner::<1>::new(NonZeroUsize::new(1024).unwrap());
1014        let fixed_size = MetaString::from(fixed_size_interner.try_intern("fixed-size-value").unwrap());
1015        assert_eq!(fixed_size.inner.get_union_type(), UnionType::InternedFixedSize);
1016        assert_eq!(
1017            discriminant_byte(&fixed_size.inner),
1018            UNION_TYPE_TAG_VALUE_INTERNED_FIXED_SIZE
1019        );
1020
1021        let generic_map_interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1022        let generic_map = MetaString::from(generic_map_interner.try_intern("generic-map-value").unwrap());
1023        assert_eq!(generic_map.inner.get_union_type(), UnionType::InternedGenericMap);
1024        assert_eq!(
1025            discriminant_byte(&generic_map.inner),
1026            UNION_TYPE_TAG_VALUE_INTERNED_GENERIC_MAP
1027        );
1028    }
1029
1030    #[test]
1031    fn inlined_string_uses_every_byte_before_tag_byte() {
1032        let input = "a".repeat(INLINED_STR_MAX_LEN);
1033        let meta = MetaString::try_inline(&input).expect("input should fit exactly in inline storage");
1034
1035        assert_eq!(meta.inner.get_union_type(), UnionType::Inlined);
1036        assert_eq!(discriminant_byte(&meta.inner), INLINED_STR_MAX_LEN as u8);
1037        let inlined = unsafe { meta.inner.inlined };
1038        assert_eq!(&inlined.data[..INLINED_STR_MAX_LEN], input.as_bytes());
1039    }
1040
1041    #[test]
1042    fn inlined_string_rejects_one_byte_past_tag_byte() {
1043        let input = "a".repeat(INLINED_STR_MAX_LEN + 1);
1044
1045        assert!(MetaString::try_inline(&input).is_none());
1046    }
1047
1048    #[test]
1049    fn static_str_inlineable() {
1050        // We always use the static variant, even if the string is inlineable, because this lets us make
1051        // `from_static` const.
1052        let s = "hello";
1053        let meta = MetaString::from_static(s);
1054
1055        assert_eq!(meta.inner.get_union_type(), UnionType::Static);
1056        assert_eq!(s, &*meta);
1057        assert_eq!(s, meta.into_owned());
1058    }
1059
1060    #[test]
1061    fn static_str_not_inlineable() {
1062        let s = "hello there, world! it's me, margaret!";
1063        let meta = MetaString::from_static(s);
1064
1065        assert_eq!(s, &*meta);
1066        assert_eq!(meta.inner.get_union_type(), UnionType::Static);
1067        assert_eq!(s, meta.into_owned());
1068    }
1069
1070    #[test]
1071    fn owned_string() {
1072        let s_orig = "hello";
1073        let s = String::from(s_orig);
1074        let meta = MetaString::from(s);
1075
1076        assert_eq!(s_orig, &*meta);
1077        assert_eq!(meta.inner.get_union_type(), UnionType::Owned);
1078        assert_eq!(s_orig, meta.into_owned());
1079    }
1080
1081    #[test]
1082    fn inlined_string() {
1083        let s = "hello";
1084        let meta = MetaString::from(s);
1085
1086        assert_eq!(s, &*meta);
1087        assert_eq!(meta.inner.get_union_type(), UnionType::Inlined);
1088        assert_eq!(s, meta.into_owned());
1089    }
1090
1091    #[test]
1092    fn cow_string() {
1093        let meta = MetaString::from(Cow::Borrowed("hello"));
1094        assert_eq!(&*meta, "hello");
1095        assert_eq!(meta.inner.get_union_type(), UnionType::Inlined);
1096
1097        let long = "a borrowed string too long to inline";
1098        assert!(long.len() > INLINED_STR_MAX_LEN);
1099        let meta = MetaString::from(Cow::Borrowed(long));
1100        assert_eq!(&*meta, long);
1101        assert_eq!(meta.inner.get_union_type(), UnionType::Owned);
1102
1103        // An owned string keeps its allocation, even when it's short enough to inline.
1104        let owned = String::from("hello");
1105        let ptr = owned.as_ptr();
1106        let meta = MetaString::from(Cow::<str>::Owned(owned));
1107        assert_eq!(&*meta, "hello");
1108        assert_eq!(meta.inner.get_union_type(), UnionType::Owned);
1109        assert_eq!(meta.as_ptr(), ptr);
1110    }
1111
1112    #[test]
1113    fn interned_string() {
1114        let intern_str = "hello interned str!";
1115
1116        let fs_interner = FixedSizeInterner::<1>::new(NonZeroUsize::new(1024).unwrap());
1117        let s = fs_interner.try_intern(intern_str).unwrap();
1118        assert_eq!(intern_str, &*s);
1119
1120        let meta = MetaString::from(s);
1121        assert_eq!(intern_str, &*meta);
1122        assert_eq!(meta.inner.get_union_type(), UnionType::InternedFixedSize);
1123        assert_eq!(intern_str, meta.into_owned());
1124
1125        let gm_interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1126        let s = gm_interner.try_intern(intern_str).unwrap();
1127        assert_eq!(intern_str, &*s);
1128
1129        let meta = MetaString::from(s);
1130        assert_eq!(intern_str, &*meta);
1131        assert_eq!(meta.inner.get_union_type(), UnionType::InternedGenericMap);
1132        assert_eq!(intern_str, meta.into_owned());
1133    }
1134
1135    #[test]
1136    fn shared_string() {
1137        let shared_str = "hello shared str!";
1138
1139        let s = Arc::<str>::from(shared_str);
1140        assert_eq!(shared_str, &*s);
1141
1142        let meta = MetaString::from(s);
1143        assert_eq!(shared_str, &*meta);
1144        assert_eq!(meta.inner.get_union_type(), UnionType::Shared);
1145        assert_eq!(shared_str, meta.into_owned());
1146    }
1147
1148    #[test]
1149    fn meta_string_sorts_by_string_value() {
1150        let mut values = [
1151            MetaString::from("gamma"),
1152            MetaString::from("alpha"),
1153            MetaString::from("beta"),
1154        ];
1155        values.sort();
1156
1157        assert_eq!(
1158            values.iter().map(|value| &**value).collect::<Vec<_>>(),
1159            ["alpha", "beta", "gamma"]
1160        );
1161    }
1162
1163    #[test]
1164    fn protobuf_chars_conversions_preserve_value() {
1165        let chars: protobuf::Chars = MetaString::from("protobuf-value").into();
1166        let chars_ref: &str = chars.as_ref();
1167        assert_eq!(chars_ref, "protobuf-value");
1168
1169        let meta = MetaString::from("protobuf-ref-value");
1170        let chars: protobuf::Chars = (&meta).into();
1171        let chars_ref: &str = chars.as_ref();
1172        assert_eq!(chars_ref, "protobuf-ref-value");
1173    }
1174
1175    #[test]
1176    fn cheap_meta_string_trait_reports_cheap_clone_availability() {
1177        let shared = MetaString::from(Arc::<str>::from("shared-value"));
1178        assert_eq!(shared.try_cheap_clone().as_deref(), Some("shared-value"));
1179
1180        let owned = MetaString::from(String::from("owned-value"));
1181        assert!(owned.try_cheap_clone().is_none());
1182    }
1183
1184    #[test]
1185    fn shared_string_clone() {
1186        let shared_str = "hello shared str!";
1187        let s = Arc::<str>::from(shared_str);
1188        let meta = MetaString::from(s);
1189
1190        // Clone the `MetaString` to make sure we can still access the original string.
1191        let meta2 = meta.clone();
1192        assert_eq!(shared_str, &*meta2);
1193
1194        // Drop the original `MetaString` to ensure we can still access the string from our clone after going through
1195        // the drop logic for the shared variant.
1196        drop(meta);
1197        assert_eq!(shared_str, &*meta2);
1198    }
1199
1200    #[test]
1201    fn empty_string_shared() {
1202        let shared_str = "";
1203
1204        let s = Arc::<str>::from(shared_str);
1205        assert_eq!(shared_str, &*s);
1206
1207        let meta = MetaString::from(s);
1208        assert_eq!(shared_str, &*meta);
1209        assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1210        assert_eq!(shared_str, meta.into_owned());
1211    }
1212
1213    #[test]
1214    fn empty_string_interned() {
1215        let intern_str = "";
1216
1217        let interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1218        let s = interner.try_intern(intern_str).unwrap();
1219        assert_eq!(intern_str, &*s);
1220
1221        let meta = MetaString::from(s);
1222        assert_eq!(intern_str, &*meta);
1223        assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1224        assert_eq!(intern_str, meta.into_owned());
1225    }
1226
1227    #[test]
1228    fn empty_string_static() {
1229        let s = "";
1230
1231        let meta = MetaString::from_static(s);
1232        assert_eq!(s, &*meta);
1233        assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1234        assert_eq!(s, meta.into_owned());
1235    }
1236
1237    #[test]
1238    fn empty_string_inlined() {
1239        let s = "";
1240
1241        let meta = MetaString::try_inline(s).expect("empty string definitely 'fits'");
1242        assert_eq!(s, &*meta);
1243        assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1244        assert_eq!(s, meta.into_owned());
1245    }
1246
1247    #[test]
1248    fn empty_string_owned() {
1249        // When a string has capacity, we don't care if it's actually empty or not, because we want to preserve the
1250        // allocation... so our string here is empty but _does_ have capacity.
1251        let s = String::with_capacity(32);
1252        let actual_cap = s.capacity();
1253
1254        let meta = MetaString::from(s);
1255        assert_eq!("", &*meta);
1256        assert_eq!(meta.inner.get_union_type(), UnionType::Owned);
1257
1258        let owned = meta.into_owned();
1259        assert_eq!(owned.capacity(), actual_cap);
1260        assert_eq!("", owned);
1261    }
1262
1263    #[test]
1264    fn empty_string_owned_zero_capacity() {
1265        // When a string has _no_ capacity, it's effectively empty, and we treat it that way.
1266        let s = String::new();
1267
1268        let meta = MetaString::from(s);
1269        assert_eq!("", &*meta);
1270        assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1271        assert_eq!("", meta.into_owned());
1272    }
1273
1274    #[test]
1275    fn is_cheaply_cloneable() {
1276        // Owned strings are never cheap to clone.
1277        let s =
1278            String::from("big ol' stringy string that can't be inlined and lives out its bleak existence in the heap");
1279        let ms = MetaString::from(s);
1280        assert!(!ms.is_cheaply_cloneable());
1281
1282        // Empty strings are always cheap to clone.
1283        let ms = MetaString::empty();
1284        assert!(ms.is_cheaply_cloneable());
1285
1286        // Inlined strings are always cheap to clone.
1287        let s = "hello";
1288        let ms = MetaString::try_inline(s).expect("inlined string should fit");
1289        assert!(ms.is_cheaply_cloneable());
1290
1291        // Static strings are always cheap to clone.
1292        let s = "hello there, world! it's me, margaret!";
1293        let ms = MetaString::from_static(s);
1294        assert!(ms.is_cheaply_cloneable());
1295
1296        // Interned strings are always cheap to clone.
1297        let interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1298        let s = interner.try_intern("hello interned str!").unwrap();
1299        let ms = MetaString::from(s);
1300        assert!(ms.is_cheaply_cloneable());
1301
1302        // Shared strings are always cheap to clone.
1303        let s = Arc::from("hello shared str!");
1304        let ms = MetaString::from(s);
1305        assert!(ms.is_cheaply_cloneable());
1306    }
1307
1308    /// A string long enough that it can neither be inlined (>23 bytes) nor mistaken for an inlined string, used to
1309    /// force the non-inlined `MetaString` variants (owned/static/interned/shared).
1310    const LONG: &str = "this string is definitely longer than twenty-three bytes";
1311
1312    fn hash_of(ms: &MetaString) -> u64 {
1313        use std::hash::{Hash as _, Hasher as _};
1314
1315        let mut hasher = std::collections::hash_map::DefaultHasher::new();
1316        ms.hash(&mut hasher);
1317        hasher.finish()
1318    }
1319
1320    #[test]
1321    fn serde_round_trips_every_variant() {
1322        // The custom `Serialize`/`Deserialize` (a hand-written `Visitor`) must survive a real format round-trip for
1323        // every backing variant. Deserialization always reconstructs an inlined/owned string, so the invariant is
1324        // content equality, not variant identity.
1325        let interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1326        let cases: Vec<(MetaString, &str)> = vec![
1327            (MetaString::empty(), ""),
1328            (MetaString::try_inline("hi").expect("fits inline"), "hi"),
1329            (MetaString::from_static(LONG), LONG),
1330            (MetaString::from(String::from(LONG)), LONG),
1331            (MetaString::from(interner.try_intern(LONG).expect("interns")), LONG),
1332            (MetaString::from(Arc::<str>::from(LONG)), LONG),
1333        ];
1334
1335        for (ms, expected) in cases {
1336            let json = serde_json::to_string(&ms).expect("serialization should succeed");
1337
1338            // Decoding the JSON as a plain `String` confirms the serialized form carries the raw string content.
1339            let as_plain: String = serde_json::from_str(&json).expect("serialized form should be a JSON string");
1340            assert_eq!(as_plain, expected, "serialized form should carry the string content");
1341
1342            let back: MetaString = serde_json::from_str(&json).expect("deserialization should succeed");
1343            assert_eq!(back, expected, "deserialized value should match the original content");
1344            assert_eq!(ms, back, "round-trip should preserve equality");
1345        }
1346    }
1347
1348    #[test]
1349    fn equal_content_hashes_equally_across_variants() {
1350        // `Hash` delegates to the string content, so two `MetaString`s holding identical bytes must hash equally even
1351        // when they use entirely different backing variants (otherwise they'd behave inconsistently as map keys).
1352        let interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1353        let variants = [
1354            MetaString::from_static(LONG),
1355            MetaString::from(String::from(LONG)),
1356            MetaString::from(interner.try_intern(LONG).expect("interns")),
1357            MetaString::from(Arc::<str>::from(LONG)),
1358        ];
1359
1360        // Confirm the fixtures really do exercise distinct backing variants.
1361        assert_eq!(variants[0].inner.get_union_type(), UnionType::Static);
1362        assert_eq!(variants[1].inner.get_union_type(), UnionType::Owned);
1363        assert_eq!(variants[2].inner.get_union_type(), UnionType::InternedGenericMap);
1364        assert_eq!(variants[3].inner.get_union_type(), UnionType::Shared);
1365
1366        let expected_hash = hash_of(&variants[0]);
1367        for variant in &variants {
1368            assert_eq!(
1369                hash_of(variant),
1370                expected_hash,
1371                "hash must depend only on content, not the backing variant"
1372            );
1373            assert_eq!(
1374                *variant, variants[0],
1375                "equal content must compare equal across variants"
1376            );
1377        }
1378
1379        // An inlined short string and a static short string with the same content must also agree.
1380        let inlined = MetaString::from("short");
1381        let static_ = MetaString::from_static("short");
1382        assert_eq!(inlined.inner.get_union_type(), UnionType::Inlined);
1383        assert_eq!(static_.inner.get_union_type(), UnionType::Static);
1384        assert_eq!(hash_of(&inlined), hash_of(&static_));
1385    }
1386
1387    #[test]
1388    fn from_interner_inlines_short_strings() {
1389        // Step 1 of the documented fallback: an inlineable string is inlined and the interner is never consulted.
1390        let interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1391        let ms = MetaString::from_interner("short", &interner);
1392
1393        assert_eq!(ms.inner.get_union_type(), UnionType::Inlined);
1394        assert_eq!(ms, "short");
1395        assert_eq!(interner.len(), 0, "inlining must not add an interner entry");
1396    }
1397
1398    #[test]
1399    fn from_interner_interns_non_inlineable_strings() {
1400        // Step 2 of the documented fallback: a non-inlineable string is interned when the interner has capacity.
1401        let interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1402        assert!(LONG.len() > INLINED_STR_MAX_LEN);
1403
1404        let ms = MetaString::from_interner(LONG, &interner);
1405
1406        assert_eq!(ms.inner.get_union_type(), UnionType::InternedGenericMap);
1407        assert_eq!(ms, LONG);
1408        assert_eq!(interner.len(), 1, "the string should have been interned");
1409    }
1410
1411    #[test]
1412    fn from_interner_falls_back_to_owned_when_interner_is_full() {
1413        // Step 3 of the documented fallback: a non-inlineable string is allocated as an owned string when interning
1414        // fails (here, because the interner is far too small to hold it).
1415        let interner = GenericMapInterner::new(NonZeroUsize::new(16).unwrap());
1416        assert!(LONG.len() > INLINED_STR_MAX_LEN);
1417
1418        let ms = MetaString::from_interner(LONG, &interner);
1419
1420        assert_eq!(ms.inner.get_union_type(), UnionType::Owned);
1421        assert_eq!(ms, LONG);
1422        assert_eq!(
1423            interner.len(),
1424            0,
1425            "the interner had no room, so nothing should be interned"
1426        );
1427    }
1428
1429    fn arb_unicode_str_max_len(max_len: usize) -> impl Strategy<Value = String> {
1430        ".{0,23}".prop_filter("resulting string is too long", move |s| s.len() <= max_len)
1431    }
1432
1433    proptest! {
1434        #![proptest_config(ProptestConfig::with_cases(10000))]
1435
1436        #[test]
1437        #[cfg_attr(miri, ignore)]
1438        fn property_test_inlined_string(
1439            input in arb_unicode_str_max_len(INLINED_STR_MAX_LEN),
1440        ) {
1441            assert!(input.len() <= INLINED_STR_MAX_LEN, "input should fit in the inline buffer");
1442            let meta = MetaString::try_inline(&input).expect("input should fit");
1443
1444            if input.is_empty() {
1445                assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1446            } else {
1447                assert_eq!(input, &*meta);
1448                assert_eq!(meta.inner.get_union_type(), UnionType::Inlined);
1449            }
1450        }
1451
1452        #[test]
1453        #[cfg_attr(miri, ignore)]
1454        fn property_test_owned_string(
1455            input in ".*",
1456        ) {
1457            let is_empty = input.is_empty();
1458            let meta = MetaString::from(input);
1459
1460            if is_empty {
1461                assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1462            } else {
1463                assert_eq!(meta.inner.get_union_type(), UnionType::Owned);
1464            }
1465        }
1466    }
1467}