Skip to main content

kstring/
string.rs

1#[cfg(not(feature = "std"))]
2use alloc::string::String;
3use alloc::{borrow::Cow, fmt};
4
5use crate::stack::StackString;
6use crate::KStringCowBase;
7use crate::KStringRef;
8
9pub(crate) type StdString = String;
10
11/// A UTF-8 encoded, immutable string.
12#[deprecated(
13    since = "2.0.4",
14    note = "for alternatives, see https://github.com/rosetta-rs/string-rosetta-rs"
15)]
16pub type KString = KStringBase<crate::backend::DefaultStr>;
17
18/// A UTF-8 encoded, immutable string.
19#[derive(Clone)]
20#[repr(transparent)]
21pub struct KStringBase<B> {
22    inner: KStringInner<B>,
23}
24
25impl<B> KStringBase<B> {
26    pub const EMPTY: Self = Self::from_static("");
27
28    /// Create a new empty `KStringBase`.
29    #[inline]
30    #[must_use]
31    pub fn new() -> Self {
32        Self::EMPTY
33    }
34
35    /// Create a reference to a `'static` data.
36    #[inline]
37    #[must_use]
38    pub const fn from_static(other: &'static str) -> Self {
39        Self {
40            inner: KStringInner::from_static(other),
41        }
42    }
43
44    /// Create an inline string, if possible
45    #[inline]
46    #[must_use]
47    pub fn try_inline(other: &str) -> Option<Self> {
48        KStringInner::try_inline(other).map(|inner| Self { inner })
49    }
50}
51
52impl<B: crate::backend::HeapStr> KStringBase<B> {
53    /// Create an owned `KStringBase`.
54    #[inline]
55    #[must_use]
56    pub fn from_boxed(other: crate::backend::BoxedStr) -> Self {
57        Self {
58            inner: KStringInner::from_boxed(other),
59        }
60    }
61
62    /// Create an owned `KStringBase`.
63    #[inline]
64    #[must_use]
65    pub fn from_string(other: StdString) -> Self {
66        Self {
67            inner: KStringInner::from_string(other),
68        }
69    }
70
71    /// Create an owned `KStringBase` optimally from a reference.
72    #[inline]
73    #[must_use]
74    pub fn from_ref(other: &str) -> Self {
75        Self {
76            inner: KStringInner::from_ref(other),
77        }
78    }
79
80    /// Get a reference to the `KStringBase`.
81    #[inline]
82    #[must_use]
83    pub fn as_ref(&self) -> KStringRef<'_> {
84        self.inner.as_ref()
85    }
86
87    /// Extracts a string slice containing the entire `KStringBase`.
88    #[inline]
89    #[must_use]
90    pub fn as_str(&self) -> &str {
91        self.inner.as_str()
92    }
93
94    /// Convert to a mutable string type, cloning the data if necessary.
95    #[inline]
96    #[must_use]
97    pub fn into_string(self) -> StdString {
98        String::from(self.into_boxed_str())
99    }
100
101    /// Convert to a mutable string type, cloning the data if necessary.
102    #[inline]
103    #[must_use]
104    pub fn into_boxed_str(self) -> crate::backend::BoxedStr {
105        self.inner.into_boxed_str()
106    }
107
108    /// Convert to a Cow str
109    #[inline]
110    #[must_use]
111    pub fn into_cow_str(self) -> Cow<'static, str> {
112        self.inner.into_cow_str()
113    }
114}
115
116impl<B: crate::backend::HeapStr> core::ops::Deref for KStringBase<B> {
117    type Target = str;
118
119    #[inline]
120    fn deref(&self) -> &str {
121        self.as_str()
122    }
123}
124
125impl<B: crate::backend::HeapStr> Eq for KStringBase<B> {}
126
127impl<B: crate::backend::HeapStr> PartialEq<Self> for KStringBase<B> {
128    #[inline]
129    fn eq(&self, other: &Self) -> bool {
130        PartialEq::eq(self.as_str(), other.as_str())
131    }
132}
133
134impl<B: crate::backend::HeapStr> PartialEq<str> for KStringBase<B> {
135    #[inline]
136    fn eq(&self, other: &str) -> bool {
137        PartialEq::eq(self.as_str(), other)
138    }
139}
140
141impl<B: crate::backend::HeapStr> PartialEq<&str> for KStringBase<B> {
142    #[inline]
143    fn eq(&self, other: &&str) -> bool {
144        PartialEq::eq(self.as_str(), *other)
145    }
146}
147
148impl<B: crate::backend::HeapStr> PartialEq<String> for KStringBase<B> {
149    #[inline]
150    fn eq(&self, other: &StdString) -> bool {
151        PartialEq::eq(self.as_str(), other.as_str())
152    }
153}
154
155impl<B: crate::backend::HeapStr> Ord for KStringBase<B> {
156    #[inline]
157    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
158        self.as_str().cmp(other.as_str())
159    }
160}
161
162impl<B: crate::backend::HeapStr> PartialOrd for KStringBase<B> {
163    #[inline]
164    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
165        Some(self.cmp(other))
166    }
167}
168
169impl<B: crate::backend::HeapStr> core::hash::Hash for KStringBase<B> {
170    #[inline]
171    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
172        self.as_str().hash(state);
173    }
174}
175
176impl<B: crate::backend::HeapStr> fmt::Debug for KStringBase<B> {
177    #[inline]
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        self.as_str().fmt(f)
180    }
181}
182
183impl<B: crate::backend::HeapStr> fmt::Display for KStringBase<B> {
184    #[inline]
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        fmt::Display::fmt(self.as_str(), f)
187    }
188}
189
190impl<B: crate::backend::HeapStr> AsRef<str> for KStringBase<B> {
191    #[inline]
192    fn as_ref(&self) -> &str {
193        self.as_str()
194    }
195}
196
197impl<B: crate::backend::HeapStr> AsRef<[u8]> for KStringBase<B> {
198    #[inline]
199    fn as_ref(&self) -> &[u8] {
200        self.as_bytes()
201    }
202}
203
204#[cfg(feature = "std")]
205impl<B: crate::backend::HeapStr> AsRef<std::ffi::OsStr> for KStringBase<B> {
206    #[inline]
207    fn as_ref(&self) -> &std::ffi::OsStr {
208        (**self).as_ref()
209    }
210}
211
212#[cfg(feature = "std")]
213impl<B: crate::backend::HeapStr> AsRef<std::path::Path> for KStringBase<B> {
214    #[inline]
215    fn as_ref(&self) -> &std::path::Path {
216        std::path::Path::new(self)
217    }
218}
219
220impl<B: crate::backend::HeapStr> alloc::borrow::Borrow<str> for KStringBase<B> {
221    #[inline]
222    fn borrow(&self) -> &str {
223        self.as_str()
224    }
225}
226
227impl<B: crate::backend::HeapStr> Default for KStringBase<B> {
228    #[inline]
229    fn default() -> Self {
230        Self::new()
231    }
232}
233
234impl<'s, B: crate::backend::HeapStr> From<KStringRef<'s>> for KStringBase<B> {
235    #[inline]
236    fn from(other: KStringRef<'s>) -> Self {
237        other.to_owned()
238    }
239}
240
241impl<'s, B: crate::backend::HeapStr> From<&'s KStringRef<'s>> for KStringBase<B> {
242    #[inline]
243    fn from(other: &'s KStringRef<'s>) -> Self {
244        other.to_owned()
245    }
246}
247
248impl<'s, B: crate::backend::HeapStr> From<KStringCowBase<'s, B>> for KStringBase<B> {
249    #[inline]
250    fn from(other: KStringCowBase<'s, B>) -> Self {
251        other.into_owned()
252    }
253}
254
255impl<'s, B: crate::backend::HeapStr> From<&'s KStringCowBase<'s, B>> for KStringBase<B> {
256    #[inline]
257    fn from(other: &'s KStringCowBase<'s, B>) -> Self {
258        other.clone().into_owned()
259    }
260}
261
262impl<B: crate::backend::HeapStr> From<StdString> for KStringBase<B> {
263    #[inline]
264    fn from(other: StdString) -> Self {
265        Self::from_string(other)
266    }
267}
268
269impl<'s, B: crate::backend::HeapStr> From<&'s StdString> for KStringBase<B> {
270    #[inline]
271    fn from(other: &'s StdString) -> Self {
272        Self::from_ref(other)
273    }
274}
275
276impl<B: crate::backend::HeapStr> From<crate::backend::BoxedStr> for KStringBase<B> {
277    #[inline]
278    fn from(other: crate::backend::BoxedStr) -> Self {
279        Self::from_boxed(other)
280    }
281}
282
283impl<'s, B: crate::backend::HeapStr> From<&'s crate::backend::BoxedStr> for KStringBase<B> {
284    #[inline]
285    fn from(other: &'s crate::backend::BoxedStr) -> Self {
286        Self::from_ref(other)
287    }
288}
289
290impl<B: crate::backend::HeapStr> From<&'static str> for KStringBase<B> {
291    #[inline]
292    fn from(other: &'static str) -> Self {
293        Self::from_static(other)
294    }
295}
296
297impl<B: crate::backend::HeapStr> core::str::FromStr for KStringBase<B> {
298    type Err = core::convert::Infallible;
299    #[inline]
300    fn from_str(s: &str) -> Result<Self, Self::Err> {
301        Ok(Self::from_ref(s))
302    }
303}
304
305#[cfg(feature = "serde")]
306impl<B: crate::backend::HeapStr> serde::Serialize for KStringBase<B> {
307    #[inline]
308    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
309    where
310        S: serde::Serializer,
311    {
312        serializer.serialize_str(self.as_str())
313    }
314}
315
316#[cfg(feature = "serde")]
317impl<'de, B: crate::backend::HeapStr> serde::Deserialize<'de> for KStringBase<B> {
318    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
319    where
320        D: serde::Deserializer<'de>,
321    {
322        deserializer.deserialize_string(StringVisitor(core::marker::PhantomData))
323    }
324}
325
326#[cfg(feature = "serde")]
327struct StringVisitor<B>(core::marker::PhantomData<B>);
328
329#[cfg(feature = "serde")]
330impl<B: crate::backend::HeapStr> serde::de::Visitor<'_> for StringVisitor<B> {
331    type Value = KStringBase<B>;
332
333    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
334        formatter.write_str("a string")
335    }
336
337    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
338    where
339        E: serde::de::Error,
340    {
341        Ok(Self::Value::from_ref(v))
342    }
343
344    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
345    where
346        E: serde::de::Error,
347    {
348        Ok(Self::Value::from_string(v))
349    }
350
351    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
352    where
353        E: serde::de::Error,
354    {
355        match core::str::from_utf8(v) {
356            Ok(s) => Ok(Self::Value::from_ref(s)),
357            Err(_) => Err(serde::de::Error::invalid_value(
358                serde::de::Unexpected::Bytes(v),
359                &self,
360            )),
361        }
362    }
363
364    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
365    where
366        E: serde::de::Error,
367    {
368        match String::from_utf8(v) {
369            Ok(s) => Ok(Self::Value::from_string(s)),
370            Err(e) => Err(serde::de::Error::invalid_value(
371                serde::de::Unexpected::Bytes(&e.into_bytes()),
372                &self,
373            )),
374        }
375    }
376}
377
378use inner::KStringInner;
379
380#[cfg(not(feature = "unsafe"))]
381mod inner {
382    use super::*;
383
384    pub(super) enum KStringInner<B> {
385        Singleton(&'static str),
386        Inline(StackString<CAPACITY>),
387        Owned(B),
388    }
389
390    impl<B> KStringInner<B> {
391        /// Create a reference to a `'static` data.
392        #[inline]
393        pub const fn from_static(other: &'static str) -> Self {
394            Self::Singleton(other)
395        }
396
397        #[inline]
398        pub fn try_inline(other: &str) -> Option<Self> {
399            StackString::try_new(other).map(Self::Inline)
400        }
401    }
402
403    impl<B: crate::backend::HeapStr> KStringInner<B> {
404        #[inline]
405        pub(super) fn from_boxed(other: crate::backend::BoxedStr) -> Self {
406            #[allow(clippy::useless_conversion)]
407            Self::Owned(B::from_boxed_str(other))
408        }
409
410        #[inline]
411        pub(super) fn from_string(other: StdString) -> Self {
412            if (0..=CAPACITY).contains(&other.len()) {
413                let inline = { StackString::new(other.as_str()) };
414                Self::Inline(inline)
415            } else {
416                Self::from_boxed(other.into_boxed_str())
417            }
418        }
419
420        #[inline]
421        pub(super) fn from_ref(other: &str) -> Self {
422            if (0..=CAPACITY).contains(&other.len()) {
423                let inline = { StackString::new(other) };
424                Self::Inline(inline)
425            } else {
426                Self::Owned(B::from_str(other))
427            }
428        }
429
430        #[inline]
431        pub(super) fn as_ref(&self) -> KStringRef<'_> {
432            match self {
433                Self::Singleton(s) => KStringRef::from_static(s),
434                Self::Inline(s) => KStringRef::from_ref(s.as_str()),
435                Self::Owned(s) => KStringRef::from_ref(s.as_str()),
436            }
437        }
438
439        #[inline]
440        pub(super) fn as_str(&self) -> &str {
441            match self {
442                Self::Singleton(s) => s,
443                Self::Inline(s) => s.as_str(),
444                Self::Owned(s) => s.as_str(),
445            }
446        }
447
448        #[inline]
449        pub(super) fn into_boxed_str(self) -> crate::backend::BoxedStr {
450            match self {
451                Self::Singleton(s) => crate::backend::BoxedStr::from(s),
452                Self::Inline(s) => crate::backend::BoxedStr::from(s.as_str()),
453                Self::Owned(s) => crate::backend::BoxedStr::from(s.as_str()),
454            }
455        }
456
457        /// Convert to a Cow str
458        #[inline]
459        pub(super) fn into_cow_str(self) -> Cow<'static, str> {
460            match self {
461                Self::Singleton(s) => Cow::Borrowed(s),
462                Self::Inline(s) => Cow::Owned(s.as_str().into()),
463                Self::Owned(s) => Cow::Owned(s.as_str().into()),
464            }
465        }
466    }
467
468    // Explicit to avoid inlining which cuts clone times in half.
469    //
470    // An automatically derived `clone()` has 10ns overhead while the explicit `Deref`/`as_str` has
471    // none of that.  Being explicit and removing the `#[inline]` attribute dropped the overhead to
472    // 5ns.
473    //
474    // My only guess is that the `clone()` calls we delegate to are just that much bigger than
475    // `as_str()` that, when combined with a jump table, is blowing the icache, slowing things down.
476    impl<B: Clone> Clone for KStringInner<B> {
477        fn clone(&self) -> Self {
478            match self {
479                Self::Singleton(s) => Self::Singleton(s),
480                Self::Inline(s) => Self::Inline(*s),
481                Self::Owned(s) => Self::Owned(s.clone()),
482            }
483        }
484    }
485
486    #[allow(unused)]
487    const LEN_SIZE: usize = core::mem::size_of::<crate::stack::Len>();
488
489    #[allow(unused)]
490    const TAG_SIZE: usize = core::mem::size_of::<u8>();
491
492    #[allow(unused)]
493    const MAX_CAPACITY: usize =
494        core::mem::size_of::<crate::string::StdString>() - TAG_SIZE - LEN_SIZE;
495
496    // Performance seems to slow down when trying to occupy all of the padding left by `String`'s
497    // discriminant.  The question is whether faster len=1-16 "allocations" outweighs going to the heap
498    // for len=17-22.
499    #[allow(unused)]
500    const ALIGNED_CAPACITY: usize = core::mem::size_of::<crate::backend::DefaultStr>() - LEN_SIZE;
501
502    #[cfg(feature = "max_inline")]
503    const CAPACITY: usize = MAX_CAPACITY;
504    #[cfg(not(feature = "max_inline"))]
505    const CAPACITY: usize = ALIGNED_CAPACITY;
506}
507
508#[cfg(feature = "unsafe")]
509mod inner {
510    use super::{Cow, KStringRef, StackString, StdString};
511
512    #[repr(C)]
513    pub(super) union KStringInner<B> {
514        tag: TagVariant,
515        singleton: SingletonVariant,
516        owned: core::mem::ManuallyDrop<OwnedVariant<B>>,
517        inline: InlineVariant,
518    }
519
520    impl<B> KStringInner<B> {
521        /// Create a reference to a `'static` data.
522        #[inline]
523        pub(super) const fn from_static(other: &'static str) -> Self {
524            Self {
525                singleton: SingletonVariant::new(other),
526            }
527        }
528
529        #[inline]
530        pub(super) fn try_inline(other: &str) -> Option<Self> {
531            StackString::try_new(other).map(|inline| Self {
532                inline: InlineVariant::new(inline),
533            })
534        }
535
536        #[inline]
537        const fn tag(&self) -> Tag {
538            unsafe {
539                // SAFETY: `tag` is in the same spot in each variant
540                self.tag.tag
541            }
542        }
543    }
544
545    impl<B: crate::backend::HeapStr> KStringInner<B> {
546        #[inline]
547        pub(super) fn from_boxed(other: crate::backend::BoxedStr) -> Self {
548            #[allow(clippy::useless_conversion)]
549            let payload = B::from_boxed_str(other);
550            Self {
551                owned: core::mem::ManuallyDrop::new(OwnedVariant::new(payload)),
552            }
553        }
554
555        #[inline]
556        pub(super) fn from_string(other: StdString) -> Self {
557            if (0..=CAPACITY).contains(&other.len()) {
558                let payload = unsafe {
559                    // SAFETY: range check ensured this is always safe
560                    StackString::new_unchecked(other.as_str())
561                };
562                Self {
563                    inline: InlineVariant::new(payload),
564                }
565            } else {
566                Self::from_boxed(other.into_boxed_str())
567            }
568        }
569
570        #[inline]
571        pub(super) fn from_ref(other: &str) -> Self {
572            if (0..=CAPACITY).contains(&other.len()) {
573                let payload = unsafe {
574                    // SAFETY: range check ensured this is always safe
575                    StackString::new_unchecked(other)
576                };
577                Self {
578                    inline: InlineVariant::new(payload),
579                }
580            } else {
581                #[allow(clippy::useless_conversion)]
582                let payload = B::from_str(other);
583                Self {
584                    owned: core::mem::ManuallyDrop::new(OwnedVariant::new(payload)),
585                }
586            }
587        }
588
589        #[inline]
590        pub(super) fn as_ref(&self) -> KStringRef<'_> {
591            let tag = self.tag();
592            unsafe {
593                // SAFETY: `tag` ensures access to correct variant
594                if tag.is_singleton() {
595                    KStringRef::from_static(self.singleton.payload)
596                } else if tag.is_owned() {
597                    KStringRef::from_ref(self.owned.payload.as_str())
598                } else {
599                    debug_assert!(tag.is_inline());
600                    KStringRef::from_ref(self.inline.payload.as_str())
601                }
602            }
603        }
604
605        #[inline]
606        pub(super) fn as_str(&self) -> &str {
607            let tag = self.tag();
608            unsafe {
609                // SAFETY: `tag` ensures access to correct variant
610                if tag.is_singleton() {
611                    self.singleton.payload
612                } else if tag.is_owned() {
613                    self.owned.payload.as_str()
614                } else {
615                    debug_assert!(tag.is_inline());
616                    self.inline.payload.as_str()
617                }
618            }
619        }
620
621        #[inline]
622        pub(super) fn into_boxed_str(self) -> crate::backend::BoxedStr {
623            let tag = self.tag();
624            unsafe {
625                // SAFETY: `tag` ensures access to correct variant
626                if tag.is_singleton() {
627                    crate::backend::BoxedStr::from(self.singleton.payload)
628                } else if tag.is_owned() {
629                    crate::backend::BoxedStr::from(self.owned.payload.as_str())
630                } else {
631                    debug_assert!(tag.is_inline());
632                    crate::backend::BoxedStr::from(self.inline.payload.as_ref())
633                }
634            }
635        }
636
637        /// Convert to a Cow str
638        #[inline]
639        pub(super) fn into_cow_str(self) -> Cow<'static, str> {
640            let tag = self.tag();
641            unsafe {
642                // SAFETY: `tag` ensures access to correct variant
643                if tag.is_singleton() {
644                    Cow::Borrowed(self.singleton.payload)
645                } else if tag.is_owned() {
646                    Cow::Owned(self.owned.payload.as_str().into())
647                } else {
648                    debug_assert!(tag.is_inline());
649                    Cow::Owned(self.inline.payload.as_str().into())
650                }
651            }
652        }
653    }
654
655    // Explicit to avoid inlining which cuts clone times in half.
656    //
657    // An automatically derived `clone()` has 10ns overhead while the explicit `Deref`/`as_str` has
658    // none of that.  Being explicit and removing the `#[inline]` attribute dropped the overhead to
659    // 5ns.
660    //
661    // My only guess is that the `clone()` calls we delegate to are just that much bigger than
662    // `as_str()` that, when combined with a jump table, is blowing the icache, slowing things down.
663    impl<B: Clone> Clone for KStringInner<B> {
664        fn clone(&self) -> Self {
665            let tag = self.tag();
666            if tag.is_owned() {
667                unsafe {
668                    // SAFETY: `tag` ensures access to correct variant
669                    Self {
670                        owned: core::mem::ManuallyDrop::new(OwnedVariant::new(
671                            self.owned.payload.clone(),
672                        )),
673                    }
674                }
675            } else {
676                unsafe {
677                    // SAFETY: `tag` ensures access to correct variant
678                    // SAFETY: non-owned types are copyable
679                    core::mem::transmute_copy(self)
680                }
681            }
682        }
683    }
684
685    impl<B> Drop for KStringInner<B> {
686        fn drop(&mut self) {
687            let tag = self.tag();
688            if tag.is_owned() {
689                unsafe {
690                    // SAFETY: `tag` ensures we are using the right variant
691                    core::mem::ManuallyDrop::drop(&mut self.owned);
692                }
693            }
694        }
695    }
696
697    #[allow(unused)]
698    const LEN_SIZE: usize = size_of::<crate::stack::Len>();
699
700    #[allow(unused)]
701    const TAG_SIZE: usize = size_of::<Tag>();
702
703    #[allow(unused)]
704    const PAYLOAD_SIZE: usize = size_of::<crate::backend::DefaultStr>();
705    type Payload = Padding<PAYLOAD_SIZE>;
706
707    #[allow(unused)]
708    const TARGET_SIZE: usize = size_of::<Target>();
709    type Target = StdString;
710
711    #[allow(unused)]
712    const MAX_CAPACITY: usize = TARGET_SIZE - LEN_SIZE - TAG_SIZE;
713
714    // Performance seems to slow down when trying to occupy all of the padding left by `String`'s
715    // discriminant.  The question is whether faster len=1-16 "allocations" outweighs going to the heap
716    // for len=17-22.
717    #[allow(unused)]
718    const ALIGNED_CAPACITY: usize = PAYLOAD_SIZE - LEN_SIZE;
719
720    #[cfg(feature = "max_inline")]
721    const CAPACITY: usize = MAX_CAPACITY;
722    #[cfg(not(feature = "max_inline"))]
723    const CAPACITY: usize = ALIGNED_CAPACITY;
724
725    const PAYLOAD_PAD_SIZE: usize = TARGET_SIZE - PAYLOAD_SIZE - TAG_SIZE;
726    const INLINE_PAD_SIZE: usize = TARGET_SIZE - CAPACITY - LEN_SIZE - TAG_SIZE;
727
728    #[derive(Copy, Clone)]
729    #[repr(C)]
730    struct TagVariant {
731        payload: Payload,
732        pad: Padding<PAYLOAD_PAD_SIZE>,
733        tag: Tag,
734    }
735    static_assertions::assert_eq_size!(Target, TagVariant);
736
737    #[derive(Copy, Clone)]
738    #[repr(C)]
739    struct SingletonVariant {
740        payload: &'static str,
741        pad: Padding<PAYLOAD_PAD_SIZE>,
742        tag: Tag,
743    }
744    static_assertions::assert_eq_size!(Payload, &'static str);
745    static_assertions::assert_eq_size!(Target, SingletonVariant);
746
747    impl SingletonVariant {
748        #[inline]
749        const fn new(payload: &'static str) -> Self {
750            Self {
751                payload,
752                pad: Padding::new(),
753                tag: Tag::SINGLETON,
754            }
755        }
756    }
757
758    impl core::fmt::Debug for SingletonVariant {
759        #[inline]
760        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
761            self.payload.fmt(f)
762        }
763    }
764
765    #[derive(Clone)]
766    #[repr(C)]
767    struct OwnedVariant<B> {
768        payload: B,
769        pad: Padding<PAYLOAD_PAD_SIZE>,
770        tag: Tag,
771    }
772    static_assertions::assert_eq_size!(Payload, crate::backend::DefaultStr);
773    static_assertions::assert_eq_size!(Target, OwnedVariant<crate::backend::DefaultStr>);
774
775    impl<B> OwnedVariant<B> {
776        #[inline]
777        const fn new(payload: B) -> Self {
778            Self {
779                payload,
780                pad: Padding::new(),
781                tag: Tag::OWNED,
782            }
783        }
784    }
785
786    impl<B: crate::backend::HeapStr> core::fmt::Debug for OwnedVariant<B> {
787        #[inline]
788        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
789            self.payload.fmt(f)
790        }
791    }
792
793    #[derive(Copy, Clone)]
794    #[repr(C)]
795    struct InlineVariant {
796        payload: StackString<CAPACITY>,
797        pad: Padding<INLINE_PAD_SIZE>,
798        tag: Tag,
799    }
800    static_assertions::assert_eq_size!(Target, InlineVariant);
801
802    impl InlineVariant {
803        #[inline]
804        const fn new(payload: StackString<CAPACITY>) -> Self {
805            Self {
806                payload,
807                pad: Padding::new(),
808                tag: Tag::INLINE,
809            }
810        }
811    }
812
813    impl core::fmt::Debug for InlineVariant {
814        #[inline]
815        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
816            self.payload.fmt(f)
817        }
818    }
819
820    #[derive(Copy, Clone, PartialEq, Eq)]
821    #[repr(transparent)]
822    struct Tag(u8);
823
824    impl Tag {
825        const SINGLETON: Self = Self(0);
826        const OWNED: Self = Self(u8::MAX);
827        const INLINE: Self = Self(1);
828
829        #[inline]
830        const fn is_singleton(self) -> bool {
831            self.0 == Self::SINGLETON.0
832        }
833
834        #[inline]
835        const fn is_owned(self) -> bool {
836            self.0 == Self::OWNED.0
837        }
838
839        #[inline]
840        const fn is_inline(self) -> bool {
841            !self.is_singleton() && !self.is_owned()
842        }
843    }
844
845    #[derive(Copy, Clone)]
846    #[repr(transparent)]
847    struct Padding<const L: usize>([core::mem::MaybeUninit<u8>; L]);
848
849    impl<const L: usize> Padding<L> {
850        const fn new() -> Self {
851            let padding = unsafe {
852                // SAFETY: Padding, never actually used
853                core::mem::MaybeUninit::uninit().assume_init()
854            };
855            Self(padding)
856        }
857    }
858
859    impl<const L: usize> Default for Padding<L> {
860        fn default() -> Self {
861            Self::new()
862        }
863    }
864}
865
866#[cfg(test)]
867mod test {
868    use super::*;
869
870    #[test]
871    fn test_size() {
872        println!("KString: {}", size_of::<KString>());
873    }
874}