Skip to main content

kstring/
backend.rs

1#[cfg(not(feature = "std"))]
2use alloc::boxed::Box;
3#[cfg(not(feature = "std"))]
4use alloc::string::String;
5
6#[cfg(feature = "arc")]
7pub(crate) type DefaultStr = ArcStr;
8#[cfg(not(feature = "arc"))]
9pub(crate) type DefaultStr = BoxedStr;
10
11/// Fast allocations, O(n) clones
12pub type BoxedStr = Box<str>;
13static_assertions::assert_eq_size!(DefaultStr, BoxedStr);
14
15/// Cross-thread, O(1) clones
16pub type ArcStr = alloc::sync::Arc<str>;
17static_assertions::assert_eq_size!(DefaultStr, ArcStr);
18
19/// O(1) clones
20pub type RcStr = alloc::rc::Rc<str>;
21static_assertions::assert_eq_size!(DefaultStr, RcStr);
22
23/// Abstract over different type of heap-allocated strings
24pub trait HeapStr: core::fmt::Debug + Clone + private::Sealed {
25    fn from_str(other: &str) -> Self;
26    fn from_string(other: String) -> Self;
27    fn from_boxed_str(other: BoxedStr) -> Self;
28    fn as_str(&self) -> &str;
29}
30
31impl HeapStr for BoxedStr {
32    #[inline]
33    fn from_str(other: &str) -> Self {
34        other.into()
35    }
36
37    #[inline]
38    fn from_string(other: String) -> Self {
39        other.into_boxed_str()
40    }
41
42    #[inline]
43    fn from_boxed_str(other: BoxedStr) -> Self {
44        other
45    }
46
47    #[inline]
48    fn as_str(&self) -> &str {
49        self
50    }
51}
52
53impl HeapStr for ArcStr {
54    #[inline]
55    fn from_str(other: &str) -> Self {
56        other.into()
57    }
58
59    #[inline]
60    fn from_string(other: String) -> Self {
61        other.into_boxed_str().into()
62    }
63
64    #[inline]
65    fn from_boxed_str(other: BoxedStr) -> Self {
66        other.into()
67    }
68
69    #[inline]
70    fn as_str(&self) -> &str {
71        self
72    }
73}
74
75impl HeapStr for RcStr {
76    #[inline]
77    fn from_str(other: &str) -> Self {
78        other.into()
79    }
80
81    #[inline]
82    fn from_string(other: String) -> Self {
83        other.into_boxed_str().into()
84    }
85
86    #[inline]
87    fn from_boxed_str(other: BoxedStr) -> Self {
88        other.into()
89    }
90
91    #[inline]
92    fn as_str(&self) -> &str {
93        self
94    }
95}
96
97pub(crate) mod private {
98    pub trait Sealed {}
99    impl Sealed for super::BoxedStr {}
100    impl Sealed for super::ArcStr {}
101    impl Sealed for super::RcStr {}
102}