ref_str 0.2.0

Compressed borrowed-or-shared string types for no_std Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
//! Compact borrowed-or-shared string types for `no_std` Rust.
//!
//! `ref_str` stores either:
//! - a borrowed `&str`,
//! - an inline short string stored inside the value itself, or
//! - a shared owned string backed by [`Arc<str>`] or [`Rc<str>`]
//!
//! The public wrappers sit on top of a compact two-word core representation, so
//! they are useful when you want to preserve borrowing when possible while still
//! supporting cheap clones of owned values.
//!
//! # Type Families
//!
//! [`RefStr<'a>`] and [`StaticRefStr`] use [`Arc<str>`] for shared ownership and
//! are appropriate when values may cross thread boundaries.
//!
//! [`LocalRefStr<'a>`] and [`LocalStaticRefStr`] use [`Rc<str>`] instead, which
//! avoids atomic reference counting in single-threaded contexts.
//!
//! The lifetime-parameterized wrappers can preserve borrowed data during
//! deserialization. The dedicated `'static` wrappers always deserialize into
//! owned storage, even when the input format exposes borrowed strings.
//!
//! # Borrowed vs Shared
//!
//! Each value is always in exactly one of three states:
//! - borrowed, exposed by [`is_borrowed`](RefStr::is_borrowed)
//! - inline, exposed by [`is_inline`](RefStr::is_inline)
//! - shared, exposed by [`is_shared`](RefStr::is_shared)
//!
//! Borrowed values preserve the original lifetime and can be recovered as `&str`
//! or `Cow<'a, str>` without allocation. Inline values own short strings inside
//! the compact two-word payload. Shared values own their backing allocation
//! through `Arc<str>` or `Rc<str>`, and cloning them only bumps the reference
//! count.
//!
//! # Common Operations
//!
//! All four public wrappers expose the same core operations:
//! - constructors such as [`new`](RefStr::new), [`from_str`](RefStr::from_str),
//!   [`from_owned_like`](RefStr::from_owned_like), [`from_shared`](RefStr::from_shared),
//!   and [`from_static`](StaticRefStr::from_static) for the dedicated static types
//! - state inspection via [`is_borrowed`](RefStr::is_borrowed),
//!   [`is_inline`](RefStr::is_inline), [`is_shared`](RefStr::is_shared),
//!   [`is_ascii`](RefStr::is_ascii), [`len`](RefStr::len), and
//!   [`is_empty`](RefStr::is_empty)
//! - string access through [`as_str`](RefStr::as_str), [`as_cow`](RefStr::as_cow),
//!   [`into_cow`](RefStr::into_cow), [`into_string`](RefStr::into_string),
//!   [`into_boxed_str`](RefStr::into_boxed_str), and [`into_bytes`](RefStr::into_bytes)
//! - content-based comparisons with `&str`, [`String`], [`Cow<'_, str>`][Cow],
//!   [`Rc<str>`], and [`Arc<str>`] through [`PartialEq`]
//!
//! # Allocation Notes
//!
//! [`as_cow`](RefStr::as_cow) is allocation-free only for borrowed values. When
//! the value is shared, `as_cow` returns `Cow::Owned` and clones the string
//! contents, because a `Cow<'a, str>` cannot borrow directly from `Rc<str>` or
//! `Arc<str>`.
//!
//! Conversions between [`LocalRefStr<'a>`] and [`RefStr<'a>`] preserve borrowed
//! values without allocation. Shared values must be re-materialized into the
//! target backend, so converting between the `Rc` and `Arc` families allocates
//! and copies the string contents.
//!
//! # Advanced APIs
//!
//! Advanced raw-pointer escape hatches are available through
//! [`into_raw_parts`](RefStr::into_raw_parts),
//! [`from_raw_parts`](RefStr::from_raw_parts), [`into_raw`](RefStr::into_raw),
//! [`into_raw_shared`](RefStr::into_raw_shared), and
//! [`increment_strong_count`](RefStr::increment_strong_count).
//!
//! Most of these APIs are `unsafe`: callers must preserve the original backend,
//! ownership rules, and encoded tag values.
//!
//! [`into_raw`](RefStr::into_raw) is intentionally low-level: its returned
//! `*const str` may point to borrowed data or shared backend storage. Inline
//! values materialize shared storage before producing a raw pointer. If you
//! need a raw pointer that is guaranteed to come from shared storage, prefer
//! [`into_raw_shared`](RefStr::into_raw_shared). Passing a borrowed pointer from
//! `into_raw` into
//! [`increment_strong_count`](RefStr::increment_strong_count) is undefined
//! behavior.
//!
//! # Examples
//!
//! ```rust
//! use ref_str::{RefStr, StaticRefStr};
//!
//! let borrowed = RefStr::from("hello");
//! assert!(borrowed.is_borrowed());
//! assert_eq!(borrowed.as_str(), "hello");
//!
//! let inline = RefStr::from(String::from("world"));
//! assert!(inline.is_inline());
//! assert_eq!(inline.clone().into_string(), "world");
//!
//! let shared = RefStr::from(String::from("this string is definitely shared"));
//! assert!(shared.is_shared());
//!
//! let borrowed_cow = borrowed.as_cow();
//! assert_eq!(borrowed_cow.as_ref(), "hello");
//!
//! let static_value = StaticRefStr::from_static("fixed");
//! assert!(static_value.is_borrowed());
//! ```

#![no_std]

#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_doctests {}

#[cfg(doctest)]
#[doc = include_str!("../README_CN.md")]
mod readme_cn_doctests {}

extern crate alloc;

mod arch;
mod backend;
mod core;
mod raw;

use ::core::borrow::Borrow;
use ::core::cmp::Ordering;
use ::core::fmt;
use ::core::hash::{Hash, Hasher};
use ::core::mem::ManuallyDrop;
use ::core::ops::Deref;
use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::rc::Rc;
use alloc::string::String;
use alloc::sync::Arc;

#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Result as ArbitraryResult, Unstructured};

#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};

pub use crate::raw::RawParts;

/// A compact string that is either borrowed for `'a` or shared via [`Arc<str>`].
///
/// Use this type when you want to preserve borrowing when possible, but still
/// accept owned strings and clone them cheaply through atomic reference
/// counting.
#[repr(transparent)]
pub struct RefStr<'a>(ManuallyDrop<crate::core::RefStrCore<'a, crate::core::SharedBackend>>);

/// A compact string that is either borrowed for `'a` or shared via [`Rc<str>`].
///
/// This is the single-threaded counterpart to [`RefStr`]. It has the same API
/// shape, but shared ownership uses non-atomic reference counting.
#[repr(transparent)]
pub struct LocalRefStr<'a>(ManuallyDrop<crate::core::RefStrCore<'a, crate::core::LocalBackend>>);

/// A `'static` compact string that is either borrowed or shared via [`Arc<str>`].
///
/// Borrowed instances hold `&'static str`. Owned inputs are promoted into shared
/// storage so the resulting value remains `'static`.
#[repr(transparent)]
pub struct StaticRefStr(ManuallyDrop<crate::core::RefStrCore<'static, crate::core::SharedBackend>>);

/// A `'static` compact string that is either borrowed or shared via [`Rc<str>`].
///
/// This is the single-threaded counterpart to [`StaticRefStr`].
#[repr(transparent)]
pub struct LocalStaticRefStr(
    ManuallyDrop<crate::core::RefStrCore<'static, crate::core::LocalBackend>>,
);

macro_rules! impl_ref_str_common {
    (
        impl [$($impl_generics:tt)*] $ty:ty {
            lifetime = $lt:lifetime;
            backend = $backend:ty;
            shared = $shared:ty;
            $($methods:tt)*
        }
    ) => {
        impl $($impl_generics)* $ty {
            /// Wrap an internal core value.
            #[inline]
            const fn from_inner(inner: crate::core::RefStrCore<$lt, $backend>) -> Self {
                Self(ManuallyDrop::new(inner))
            }

            /// Borrow the internal core representation.
            #[inline]
            const fn inner(&self) -> &crate::core::RefStrCore<$lt, $backend> {
                let ptr = &self.0
                    as *const ManuallyDrop<crate::core::RefStrCore<$lt, $backend>>
                    as *const crate::core::RefStrCore<$lt, $backend>;
                unsafe { &*ptr }
            }

            #[inline]
            const unsafe fn into_raw_parts_struct(self) -> crate::RawParts {
                #[repr(C)]
                union View<T> {
                    outer: ManuallyDrop<T>,
                    parts: crate::RawParts,
                }

                let view = View {
                    outer: ManuallyDrop::new(self),
                };

                unsafe { view.parts }
            }

            #[inline]
            unsafe fn into_inner(self) -> crate::core::RefStrCore<$lt, $backend> {
                unsafe {
                    <crate::core::RefStrCore<$lt, $backend>>::from_raw_parts_struct(
                        self.into_raw_parts_struct(),
                    )
                }
            }

            /// Create a borrowed value from `&str`.
            ///
            /// This is equivalent to [`from_str`](Self::from_str).
            #[inline]
            pub const fn new(s: &$lt str) -> Self {
                Self::from_inner(<crate::core::RefStrCore<$lt, $backend>>::new(s))
            }

            /// Create a borrowed value from `&str`.
            ///
            /// The resulting value does not allocate and remains in the borrowed
            /// state.
            #[inline]
            pub const fn from_str(s: &$lt str) -> Self {
                Self::from_inner(<crate::core::RefStrCore<$lt, $backend>>::from_str(s))
            }

            /// Create an owned value from any string-like input.
            ///
            /// Unlike [`from_str`](Self::from_str), this copies the input into
            /// owned storage. Short strings are stored inline, while longer
            /// strings use the backend's shared representation.
            #[inline]
            pub fn from_owned_like<R: AsRef<str>>(s: R) -> Self {
                Self::from_inner(<crate::core::RefStrCore<$lt, $backend>>::from_owned_like(s))
            }

            /// Rebuild a value from the raw parts produced by [`into_raw_parts`](Self::into_raw_parts).
            ///
            /// # Safety
            ///
            /// `parts` must come from a compatible `$ty` value created by this
            /// crate. The pointer/metadata pair must reference valid UTF-8 and a
            /// valid encoding state for this representation.
            #[inline]
            pub const unsafe fn from_raw_parts(parts: crate::RawParts) -> Self {
                Self::from_inner(unsafe {
                    <crate::core::RefStrCore<$lt, $backend>>::from_raw_parts(parts)
                })
            }

            /// Create a value directly from the backend's shared string type.
            ///
            /// This keeps the allocation shared without copying string contents.
            #[inline]
            pub fn from_shared(s: $shared) -> Self {
                Self::from_inner(<crate::core::RefStrCore<$lt, $backend>>::from_shared(s))
            }

            /// Decompose this value into raw parts for FFI or manual ownership transfer.
            ///
            /// # Safety
            ///
            /// The returned parts transfer ownership responsibilities to the caller. You must later
            /// reconstruct the value with [`from_raw_parts`](Self::from_raw_parts) or otherwise
            /// release the underlying shared allocation exactly once.
            #[inline]
            pub const unsafe fn into_raw_parts(self) -> crate::RawParts {
                unsafe { self.into_raw_parts_struct() }
            }

            /// Convert this value into a raw `*const str`.
            ///
            /// # Safety
            ///
            /// The returned pointer is ambiguous: it may represent either borrowed data or shared
            /// backend storage.
            ///
            /// Only pointers originating from shared values may be used with
            /// [`increment_strong_count`](Self::increment_strong_count) or reconstructed into backend
            /// shared handles.
            ///
            /// If you need to branch on ownership state, prefer
            /// [`into_raw_parts`](Self::into_raw_parts) or
            /// [`into_raw_shared`](Self::into_raw_shared).
            #[inline]
            pub unsafe fn into_raw(self) -> *const str {
                unsafe { self.into_inner().into_raw() }
            }

            /// Convert into a raw pointer only when this value is shared.
            ///
            /// Returns `None` for borrowed values, avoiding ambiguous raw pointers in mixed
            /// borrowed/shared code paths.
            #[inline]
            pub fn into_raw_shared(self) -> Option<*const str> {
                unsafe { self.into_inner() }.into_raw_shared()
            }

            /// Increment the strong count for a raw pointer produced by [`into_raw`](Self::into_raw).
            ///
            /// # Safety
            ///
            /// `ptr` must have been produced by this crate for the same backend and must still point
            /// to a live shared allocation. Calling this on a borrowed string pointer or an invalid
            /// pointer is undefined behavior.
            #[inline]
            pub unsafe fn increment_strong_count(ptr: *const str) {
                unsafe {
                    <crate::core::RefStrCore<$lt, $backend>>::increment_strong_count(ptr);
                }
            }

            /// Returns `true` when this value owns shared storage.
            #[inline]
            pub const fn is_shared(&self) -> bool {
                self.inner().is_shared()
            }

            /// Returns `true` when this value is a borrowed string.
            #[inline]
            pub const fn is_borrowed(&self) -> bool {
                self.inner().is_borrowed()
            }

            /// Returns `true` when this value stores an inline short string.
            #[inline]
            pub const fn is_inline(&self) -> bool {
                self.inner().is_inline()
            }

            /// Returns `true` when the cached contents are ASCII-only.
            #[inline]
            pub const fn is_ascii(&self) -> bool {
                self.inner().is_ascii()
            }

            /// Returns the string length in bytes.
            #[inline]
            pub const fn len(&self) -> usize {
                self.inner().len()
            }

            /// Returns `true` when the string is empty.
            #[inline]
            pub const fn is_empty(&self) -> bool {
                self.inner().is_empty()
            }

            /// Borrows the contents as `&str`.
            #[inline]
            pub fn as_str(&self) -> &str {
                self.inner().as_str()
            }

            /// Converts this value into owned UTF-8 bytes.
            #[inline]
            pub fn into_bytes(self) -> alloc::vec::Vec<u8> {
                unsafe { self.into_inner() }.into_bytes()
            }

            /// Converts this value into `Box<str>`.
            #[inline]
            pub fn into_boxed_str(self) -> Box<str> {
                unsafe { self.into_inner() }.into_boxed_str()
            }

            /// Converts this value into [`String`].
            #[inline]
            pub fn into_string(self) -> String {
                unsafe { self.into_inner() }.into_string()
            }

            /// Converts this value into [`Cow<str>`][Cow].
            ///
            /// Borrowed values stay borrowed. Inline and shared values become
            /// owned strings.
            #[inline]
            pub fn into_cow(self) -> Cow<$lt, str> {
                unsafe { self.into_inner() }.into_cow()
            }

            /// Convert into `&str` without checking whether the value is borrowed.
            ///
            /// # Safety
            ///
            /// This is only sound when the value currently stores a borrowed string whose lifetime
            /// is valid for `$lt`. Calling this on a shared value can produce a dangling reference.
            #[inline]
            pub unsafe fn into_str_unchecked(self) -> &$lt str {
                unsafe { self.into_inner().into_str_unchecked() }
            }

            $($methods)*
        }

        impl $($impl_generics)* Drop for $ty {
            /// Drops the underlying string representation.
            fn drop(&mut self) {
                unsafe {
                    ManuallyDrop::drop(&mut self.0);
                }
            }
        }

        impl $($impl_generics)* Default for $ty {
            /// Creates an empty borrowed value.
            fn default() -> Self {
                Self::from_inner(<crate::core::RefStrCore<$lt, $backend>>::default())
            }
        }

        impl $($impl_generics)* AsRef<str> for $ty {
            /// Borrows the contents as `&str`.
            fn as_ref(&self) -> &str {
                self.as_str()
            }
        }

        impl $($impl_generics)* Borrow<str> for $ty {
            /// Borrows the contents as `&str`.
            fn borrow(&self) -> &str {
                self.as_str()
            }
        }

        impl $($impl_generics)* Clone for $ty {
            /// Clones the string, incrementing the shared reference count when needed.
            fn clone(&self) -> Self {
                Self::from_inner(self.inner().clone())
            }
        }

        impl $($impl_generics)* Eq for $ty {}

        impl $($impl_generics)* PartialOrd for $ty {
            /// Performs lexicographic comparison.
            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
                Some(self.cmp(other))
            }
        }

        impl $($impl_generics)* Ord for $ty {
            /// Performs lexicographic comparison.
            fn cmp(&self, other: &Self) -> Ordering {
                self.as_str().cmp(other.as_str())
            }
        }

        impl $($impl_generics)* Hash for $ty {
            /// Hashes the string contents.
            fn hash<H: Hasher>(&self, state: &mut H) {
                self.as_str().hash(state)
            }
        }

        impl $($impl_generics)* Deref for $ty {
            type Target = str;

            /// Borrows the contents as `str`.
            fn deref(&self) -> &Self::Target {
                self.as_str()
            }
        }

        impl $($impl_generics)* fmt::Debug for $ty {
            /// Formats the type and its string contents for debugging.
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                if f.alternate() {
                    let state = if self.is_shared() {
                        "Shared"
                    } else if self.is_inline() {
                        "Inline"
                    } else {
                        "Borrowed"
                    };
                    f.debug_struct(stringify!($ty))
                        .field("state", &state)
                        .field("len", &self.len())
                        .field("value", &self.as_str())
                        .finish()
                } else {
                    f.debug_tuple(stringify!($ty))
                        .field(&self.as_str())
                        .finish()
                }
            }
        }

        impl $($impl_generics)* fmt::Display for $ty {
            /// Formats the string contents.
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(self.as_str())
            }
        }

        #[cfg(feature = "serde")]
        impl $($impl_generics)* Serialize for $ty {
            /// Serializes as a plain string.
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                serializer.serialize_str(self.as_str())
            }
        }
    };
}

macro_rules! impl_ref_str_non_static {
    ($name:ident<$lt:lifetime>, $backend:ty, $shared:ty) => {
        impl<$lt> From<&$lt str> for $name<$lt> {
            /// Creates a borrowed value from `&str`.
            fn from(value: &$lt str) -> Self {
                Self::from_inner(<crate::core::RefStrCore<$lt, $backend>>::from(value))
            }
        }

        impl<$lt> From<&$lt String> for $name<$lt> {
            /// Creates a borrowed value from `&String`.
            fn from(value: &$lt String) -> Self {
                Self::from_inner(<crate::core::RefStrCore<$lt, $backend>>::from(value))
            }
        }

        impl<$lt> From<$shared> for $name<$lt> {
            /// Creates a shared value from the backend's shared string type.
            fn from(value: $shared) -> Self {
                Self::from_inner(<crate::core::RefStrCore<$lt, $backend>>::from(value))
            }
        }

        impl<$lt> From<Box<str>> for $name<$lt> {
            /// Creates an owned value from `Box<str>`.
            fn from(value: Box<str>) -> Self {
                Self::from_inner(<crate::core::RefStrCore<$lt, $backend>>::from(value))
            }
        }

        impl<$lt> From<String> for $name<$lt> {
            /// Creates an owned value from [`String`].
            fn from(value: String) -> Self {
                Self::from_inner(<crate::core::RefStrCore<$lt, $backend>>::from(value))
            }
        }

        impl<$lt> From<Cow<$lt, str>> for $name<$lt> {
            /// Creates a value from [`Cow<str>`][Cow].
            ///
            /// Borrowed `Cow` values stay borrowed, while owned values become
            /// owned storage.
            fn from(value: Cow<$lt, str>) -> Self {
                Self::from_inner(<crate::core::RefStrCore<$lt, $backend>>::from(value))
            }
        }

        impl<$lt> From<$name<$lt>> for Cow<$lt, str> {
            /// Converts into [`Cow<str>`][Cow].
            fn from(value: $name<$lt>) -> Self {
                value.into_cow()
            }
        }

        #[cfg(feature = "arbitrary")]
        impl<$lt> Arbitrary<$lt> for $name<$lt> {
            /// Generates either a borrowed or shared arbitrary string.
            fn arbitrary(u: &mut Unstructured<$lt>) -> ArbitraryResult<Self> {
                let value = <&$lt str>::arbitrary(u)?;

                if u.arbitrary::<bool>()? {
                    Ok(Self::from(String::from(value)))
                } else {
                    Ok(Self::from(value))
                }
            }
        }

        #[cfg(feature = "serde")]
        impl<'de: $lt, $lt> Deserialize<'de> for $name<$lt> {
            /// Deserializes from a string, preserving borrowed data when available.
            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                struct Visitor;

                impl<'de> serde::de::Visitor<'de> for Visitor {
                    type Value = $name<'de>;

                    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                        f.write_str("a string")
                    }

                    fn visit_borrowed_str<E: serde::de::Error>(
                        self,
                        v: &'de str,
                    ) -> Result<Self::Value, E> {
                        Ok($name::from(v))
                    }

                    fn visit_str<E: serde::de::Error>(
                        self,
                        v: &str,
                    ) -> Result<Self::Value, E> {
                        Ok($name::from(String::from(v)))
                    }

                    fn visit_string<E: serde::de::Error>(
                        self,
                        v: String,
                    ) -> Result<Self::Value, E> {
                        Ok($name::from(v))
                    }
                }

                deserializer.deserialize_str(Visitor)
            }
        }
    };
}

macro_rules! impl_ref_str_static {
    ($name:ident, $backend:ty, $shared:ty) => {
        impl From<&'static str> for $name {
            /// Creates a borrowed `'static` value from `&'static str`.
            fn from(value: &'static str) -> Self {
                Self::from_inner(<crate::core::RefStrCore<'static, $backend>>::from(value))
            }
        }

        impl From<$shared> for $name {
            /// Creates a shared `'static` value from the backend's shared string type.
            fn from(value: $shared) -> Self {
                Self::from_inner(<crate::core::RefStrCore<'static, $backend>>::from(value))
            }
        }

        impl From<Box<str>> for $name {
            /// Creates a shared `'static` value from `Box<str>`.
            fn from(value: Box<str>) -> Self {
                Self::from_inner(<crate::core::RefStrCore<'static, $backend>>::from(value))
            }
        }

        impl From<String> for $name {
            /// Creates a shared `'static` value from [`String`].
            fn from(value: String) -> Self {
                Self::from_inner(<crate::core::RefStrCore<'static, $backend>>::from(value))
            }
        }

        impl From<Cow<'static, str>> for $name {
            /// Creates a `'static` value from [`Cow<'static, str>`][Cow].
            fn from(value: Cow<'static, str>) -> Self {
                match value {
                    Cow::Borrowed(value) => Self::from(value),
                    Cow::Owned(value) => Self::from(value),
                }
            }
        }

        impl From<$name> for Cow<'static, str> {
            /// Converts into [`Cow<'static, str>`][Cow].
            fn from(value: $name) -> Self {
                value.into_cow()
            }
        }

        #[cfg(feature = "arbitrary")]
        impl<'a> Arbitrary<'a> for $name {
            /// Generates an arbitrary shared `'static` string value.
            fn arbitrary(u: &mut Unstructured<'a>) -> ArbitraryResult<Self> {
                let value = <&str>::arbitrary(u)?;
                Ok(Self::from(String::from(value)))
            }
        }

        #[cfg(feature = "serde")]
        impl<'de> Deserialize<'de> for $name {
            /// Deserializes from a string into a `'static` value.
            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                struct Visitor;

                impl<'de> serde::de::Visitor<'de> for Visitor {
                    type Value = $name;

                    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                        f.write_str("a string")
                    }

                    fn visit_borrowed_str<E: serde::de::Error>(
                        self,
                        v: &'de str,
                    ) -> Result<Self::Value, E> {
                        Ok($name::from(String::from(v)))
                    }

                    fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
                        Ok($name::from(String::from(v)))
                    }

                    fn visit_string<E: serde::de::Error>(
                        self,
                        v: String,
                    ) -> Result<Self::Value, E> {
                        Ok($name::from(v))
                    }
                }

                deserializer.deserialize_str(Visitor)
            }
        }
    };
}

macro_rules! impl_ref_str_partial_eqs {
    (for $lhs:ty { $([$($impl_generics:tt)*] $rhs:ty => |$lhs_ref:ident, $other:ident| $compare:expr;)+ }) => {
        $(
            impl_ref_str_partial_eqs!(@single [$($impl_generics)*] $lhs => $rhs, |$lhs_ref, $other| $compare);
        )+
    };
    (@single [] $lhs:ty => $rhs:ty, |$lhs_ref:ident, $other:ident| $compare:expr) => {
        impl PartialEq<$rhs> for $lhs {
            fn eq(&self, other: &$rhs) -> bool {
                let $lhs_ref = self;
                let $other = other;
                $compare
            }
        }

        impl PartialEq<$rhs> for &$lhs {
            fn eq(&self, other: &$rhs) -> bool {
                let $lhs_ref = *self;
                let $other = other;
                $compare
            }
        }

        impl PartialEq<&$rhs> for $lhs {
            fn eq(&self, other: &&$rhs) -> bool {
                let $lhs_ref = self;
                let $other = *other;
                $compare
            }
        }

    };
    (@single [$($impl_generics:tt)+] $lhs:ty => $rhs:ty, |$lhs_ref:ident, $other:ident| $compare:expr) => {
        impl<$($impl_generics)+> PartialEq<$rhs> for $lhs {
            fn eq(&self, other: &$rhs) -> bool {
                let $lhs_ref = self;
                let $other = other;
                $compare
            }
        }

        impl<$($impl_generics)+> PartialEq<$rhs> for &$lhs {
            fn eq(&self, other: &$rhs) -> bool {
                let $lhs_ref = *self;
                let $other = other;
                $compare
            }
        }

        impl<$($impl_generics)+> PartialEq<&$rhs> for $lhs {
            fn eq(&self, other: &&$rhs) -> bool {
                let $lhs_ref = self;
                let $other = *other;
                $compare
            }
        }

    };
}

impl_ref_str_common! {
    impl [<'a>] RefStr<'a> {
        lifetime = 'a;
        backend = crate::core::SharedBackend;
        shared = Arc<str>;

        /// Borrows the contents as [`Cow<str>`][Cow].
        ///
        /// Borrowed values stay borrowed. Inline and shared values allocate and
        /// clone into an owned string to satisfy the borrow semantics of `Cow`.
        #[inline]
        pub fn as_cow(&self) -> Cow<'a, str> {
            self.inner().as_cow()
        }

        /// Convert to a static RefStr.
        ///
        /// Shared values are cloned to increase the reference count.
        /// Borrowed values are copied into owned storage, preferring inline for
        /// short strings and shared storage for longer ones.
        #[inline]
        pub fn to_static_str(&self) -> StaticRefStr {
            StaticRefStr::from_inner(self.inner().to_static_core())
        }

        /// Convert to a static RefStr.
        ///
        /// Shared and inline values are transferred directly.
        /// Borrowed values are copied into owned storage, preferring inline for
        /// short strings and shared storage for longer ones.
        #[inline]
        pub fn into_static_str(self) -> StaticRefStr {
            StaticRefStr::from_inner(unsafe { self.into_inner() }.into_static_core())
        }
    }
}

impl_ref_str_common! {
    impl [<'a>] LocalRefStr<'a> {
        lifetime = 'a;
        backend = crate::core::LocalBackend;
        shared = Rc<str>;

        /// Borrows the contents as [`Cow<str>`][Cow].
        ///
        /// Borrowed values stay borrowed. Inline and shared values allocate and
        /// clone into an owned string to satisfy the borrow semantics of `Cow`.
        #[inline]
        pub fn as_cow(&self) -> Cow<'a, str> {
            self.inner().as_cow()
        }

        /// Convert to a static LocalRefStr.
        ///
        /// Shared values are cloned to increase the reference count.
        /// Borrowed values are copied into owned storage, preferring inline for
        /// short strings and shared storage for longer ones.
        #[inline]
        pub fn to_static_str(&self) -> LocalStaticRefStr {
            LocalStaticRefStr::from_inner(self.inner().to_static_core())
        }

        /// Convert to a static LocalRefStr.
        ///
        /// Shared and inline values are transferred directly.
        /// Borrowed values are copied into owned storage, preferring inline for
        /// short strings and shared storage for longer ones.
        #[inline]
        pub fn into_static_str(self) -> LocalStaticRefStr {
            LocalStaticRefStr::from_inner(unsafe { self.into_inner() }.into_static_core())
        }
    }
}

impl_ref_str_common! {
    impl [] StaticRefStr {
        lifetime = 'static;
        backend = crate::core::SharedBackend;
        shared = Arc<str>;

        /// Borrows the contents as [`Cow<'static, str>`][Cow].
        #[inline]
        pub fn as_cow(&self) -> Cow<'static, str> {
            if let Some(value) = self.inner().borrowed_static_str() {
                Cow::Borrowed(value)
            } else {
                Cow::Owned(String::from(self.as_str()))
            }
        }

        /// Creates a borrowed value from `&'static str`.
        #[inline]
        pub const fn from_static(s: &'static str) -> Self {
            Self::from_str(s)
        }
    }
}

impl_ref_str_common! {
    impl [] LocalStaticRefStr {
        lifetime = 'static;
        backend = crate::core::LocalBackend;
        shared = Rc<str>;

        /// Borrows the contents as [`Cow<'static, str>`][Cow].
        #[inline]
        pub fn as_cow(&self) -> Cow<'static, str> {
            if let Some(value) = self.inner().borrowed_static_str() {
                Cow::Borrowed(value)
            } else {
                Cow::Owned(String::from(self.as_str()))
            }
        }

        /// Creates a borrowed value from `&'static str`.
        #[inline]
        pub const fn from_static(s: &'static str) -> Self {
            Self::from_str(s)
        }
    }
}

impl_ref_str_non_static!(RefStr<'a>, crate::core::SharedBackend, Arc<str>);
impl_ref_str_non_static!(LocalRefStr<'a>, crate::core::LocalBackend, Rc<str>);
impl_ref_str_static!(StaticRefStr, crate::core::SharedBackend, Arc<str>);
impl_ref_str_static!(LocalStaticRefStr, crate::core::LocalBackend, Rc<str>);

impl_ref_str_partial_eqs! {
    for RefStr<'a> {
        ['a] RefStr<'a> => |lhs, other| lhs.inner() == other.inner();
        ['a] &str => |lhs, other| lhs.as_str() == *other;
        ['a] String => |lhs, other| lhs.as_str() == other.as_str();
        ['a, 'b] Cow<'b, str> => |lhs, other| lhs.as_str() == other.as_ref();
        ['a] Arc<str> => |lhs, other| lhs.as_str() == other.as_ref();
        ['a] Rc<str> => |lhs, other| lhs.as_str() == other.as_ref();
    }
}

impl_ref_str_partial_eqs! {
    for LocalRefStr<'a> {
        ['a] LocalRefStr<'a> => |lhs, other| lhs.inner() == other.inner();
        ['a] &str => |lhs, other| lhs.as_str() == *other;
        ['a] String => |lhs, other| lhs.as_str() == other.as_str();
        ['a, 'b] Cow<'b, str> => |lhs, other| lhs.as_str() == other.as_ref();
        ['a] Arc<str> => |lhs, other| lhs.as_str() == other.as_ref();
        ['a] Rc<str> => |lhs, other| lhs.as_str() == other.as_ref();
    }
}

impl_ref_str_partial_eqs! {
    for StaticRefStr {
        [] StaticRefStr => |lhs, other| lhs.inner() == other.inner();
        [] &str => |lhs, other| lhs.as_str() == *other;
        [] String => |lhs, other| lhs.as_str() == other.as_str();
        ['b] Cow<'b, str> => |lhs, other| lhs.as_str() == other.as_ref();
        [] Arc<str> => |lhs, other| lhs.as_str() == other.as_ref();
        [] Rc<str> => |lhs, other| lhs.as_str() == other.as_ref();
    }
}

impl_ref_str_partial_eqs! {
    for LocalStaticRefStr {
        [] LocalStaticRefStr => |lhs, other| lhs.inner() == other.inner();
        [] &str => |lhs, other| lhs.as_str() == *other;
        [] String => |lhs, other| lhs.as_str() == other.as_str();
        ['b] Cow<'b, str> => |lhs, other| lhs.as_str() == other.as_ref();
        [] Arc<str> => |lhs, other| lhs.as_str() == other.as_ref();
        [] Rc<str> => |lhs, other| lhs.as_str() == other.as_ref();
    }
}

impl<'a> From<LocalRefStr<'a>> for RefStr<'a> {
    /// Converts the local `Rc`-backed variant into the thread-safe `Arc`-backed variant.
    ///
    /// Borrowed values remain borrowed. Shared values are re-materialized into
    /// `Arc<str>`, which allocates and copies the string contents.
    fn from(value: LocalRefStr<'a>) -> Self {
        Self::from_inner(
            <crate::core::RefStrCore<'a, crate::core::SharedBackend>>::from(unsafe {
                value.into_inner()
            }),
        )
    }
}

impl<'a> From<RefStr<'a>> for LocalRefStr<'a> {
    /// Converts the thread-safe `Arc`-backed variant into the local `Rc`-backed variant.
    ///
    /// Borrowed values remain borrowed. Shared values are re-materialized into
    /// `Rc<str>`, which allocates and copies the string contents.
    fn from(value: RefStr<'a>) -> Self {
        Self::from_inner(
            <crate::core::RefStrCore<'a, crate::core::LocalBackend>>::from(unsafe {
                value.into_inner()
            }),
        )
    }
}

impl From<LocalStaticRefStr> for StaticRefStr {
    /// Converts the local `'static` variant into the thread-safe `'static` variant.
    fn from(value: LocalStaticRefStr) -> Self {
        Self::from_inner(
            <crate::core::RefStrCore<'static, crate::core::SharedBackend>>::from(unsafe {
                value.into_inner()
            }),
        )
    }
}

impl From<StaticRefStr> for LocalStaticRefStr {
    /// Converts the thread-safe `'static` variant into the local `'static` variant.
    fn from(value: StaticRefStr) -> Self {
        Self::from_inner(
            <crate::core::RefStrCore<'static, crate::core::LocalBackend>>::from(unsafe {
                value.into_inner()
            }),
        )
    }
}

impl From<StaticRefStr> for RefStr<'static> {
    /// Converts the dedicated `'static` wrapper into the lifetime-parameterized form.
    fn from(value: StaticRefStr) -> Self {
        Self::from_inner(unsafe { value.into_inner() })
    }
}

impl From<RefStr<'static>> for StaticRefStr {
    /// Converts the lifetime-parameterized `'static` form into the dedicated wrapper.
    fn from(value: RefStr<'static>) -> Self {
        Self::from_inner(unsafe { value.into_inner() })
    }
}

impl From<LocalStaticRefStr> for LocalRefStr<'static> {
    /// Converts the dedicated local `'static` wrapper into the lifetime-parameterized form.
    fn from(value: LocalStaticRefStr) -> Self {
        Self::from_inner(unsafe { value.into_inner() })
    }
}

impl From<LocalRefStr<'static>> for LocalStaticRefStr {
    /// Converts the lifetime-parameterized local `'static` form into the dedicated wrapper.
    fn from(value: LocalRefStr<'static>) -> Self {
        Self::from_inner(unsafe { value.into_inner() })
    }
}