kstring/
backend.rs

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