Skip to main content

kstring/
string_ref.rs

1#[cfg(not(feature = "std"))]
2use crate::alloc::borrow::ToOwned;
3#[cfg(not(feature = "std"))]
4use alloc::boxed::Box;
5#[cfg(not(feature = "std"))]
6use alloc::string::String;
7use core::fmt;
8
9use crate::KStringBase;
10use crate::KStringCowBase;
11
12type StdString = String;
13type BoxedStr = Box<str>;
14
15/// A reference to a UTF-8 encoded, immutable string.
16#[derive(Copy, Clone)]
17#[repr(transparent)]
18#[deprecated(
19    since = "2.0.4",
20    note = "for alternatives, see https://github.com/rosetta-rs/string-rosetta-rs"
21)]
22pub struct KStringRef<'s> {
23    pub(crate) inner: KStringRefInner<'s>,
24}
25
26#[derive(Copy, Clone, Debug)]
27pub(crate) enum KStringRefInner<'s> {
28    Borrowed(&'s str),
29    Singleton(&'static str),
30}
31
32impl<'s> KStringRef<'s> {
33    /// Create a new empty `KStringBase`.
34    #[inline]
35    #[must_use]
36    pub const fn new() -> Self {
37        Self::from_static("")
38    }
39
40    /// Create a reference to a `'static` data.
41    #[inline]
42    #[must_use]
43    pub const fn from_static(other: &'static str) -> Self {
44        Self {
45            inner: KStringRefInner::Singleton(other),
46        }
47    }
48
49    /// Create a reference to a borrowed data.
50    #[inline]
51    #[must_use]
52    pub fn from_ref(other: &'s str) -> Self {
53        Self {
54            inner: KStringRefInner::Borrowed(other),
55        }
56    }
57
58    /// Clone the data into an owned-type.
59    #[inline]
60    #[must_use]
61    #[allow(clippy::wrong_self_convention)]
62    pub fn to_owned<B: crate::backend::HeapStr>(&self) -> KStringBase<B> {
63        self.inner.to_owned()
64    }
65
66    /// Extracts a string slice containing the entire `KStringRef`.
67    #[inline]
68    #[must_use]
69    pub fn as_str(&self) -> &str {
70        self.inner.as_str()
71    }
72
73    /// Convert to a mutable string type, cloning the data if necessary.
74    #[inline]
75    #[must_use]
76    pub fn into_mut(self) -> StdString {
77        self.inner.into_mut()
78    }
79}
80
81impl KStringRefInner<'_> {
82    #[inline]
83    #[allow(clippy::wrong_self_convention)]
84    fn to_owned<B: crate::backend::HeapStr>(&self) -> KStringBase<B> {
85        match self {
86            Self::Borrowed(s) => KStringBase::from_ref(s),
87            Self::Singleton(s) => KStringBase::from_static(s),
88        }
89    }
90
91    #[inline]
92    fn as_str(&self) -> &str {
93        match self {
94            Self::Borrowed(s) => s,
95            Self::Singleton(s) => s,
96        }
97    }
98
99    #[inline]
100    fn into_mut(self) -> StdString {
101        self.as_str().to_owned()
102    }
103}
104
105impl core::ops::Deref for KStringRef<'_> {
106    type Target = str;
107
108    #[inline]
109    fn deref(&self) -> &str {
110        self.as_str()
111    }
112}
113
114impl Eq for KStringRef<'_> {}
115
116impl<'s> PartialEq<Self> for KStringRef<'s> {
117    #[inline]
118    fn eq(&self, other: &Self) -> bool {
119        PartialEq::eq(self.as_str(), other.as_str())
120    }
121}
122
123impl PartialEq<str> for KStringRef<'_> {
124    #[inline]
125    fn eq(&self, other: &str) -> bool {
126        PartialEq::eq(self.as_str(), other)
127    }
128}
129
130impl<'s> PartialEq<&'s str> for KStringRef<'s> {
131    #[inline]
132    fn eq(&self, other: &&str) -> bool {
133        PartialEq::eq(self.as_str(), *other)
134    }
135}
136
137impl PartialEq<String> for KStringRef<'_> {
138    #[inline]
139    fn eq(&self, other: &StdString) -> bool {
140        PartialEq::eq(self.as_str(), other.as_str())
141    }
142}
143
144impl Ord for KStringRef<'_> {
145    #[inline]
146    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
147        self.as_str().cmp(other.as_str())
148    }
149}
150
151impl PartialOrd for KStringRef<'_> {
152    #[inline]
153    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
154        Some(self.cmp(other))
155    }
156}
157
158impl core::hash::Hash for KStringRef<'_> {
159    #[inline]
160    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
161        self.as_str().hash(state);
162    }
163}
164
165impl fmt::Debug for KStringRef<'_> {
166    #[inline]
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        fmt::Debug::fmt(&self.inner, f)
169    }
170}
171
172impl fmt::Display for KStringRef<'_> {
173    #[inline]
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        fmt::Display::fmt(self.as_str(), f)
176    }
177}
178
179impl AsRef<str> for KStringRef<'_> {
180    #[inline]
181    fn as_ref(&self) -> &str {
182        self.as_str()
183    }
184}
185
186impl AsRef<[u8]> for KStringRef<'_> {
187    #[inline]
188    fn as_ref(&self) -> &[u8] {
189        self.as_bytes()
190    }
191}
192
193#[cfg(feature = "std")]
194impl AsRef<std::ffi::OsStr> for KStringRef<'_> {
195    #[inline]
196    fn as_ref(&self) -> &std::ffi::OsStr {
197        (**self).as_ref()
198    }
199}
200
201#[cfg(feature = "std")]
202impl AsRef<std::path::Path> for KStringRef<'_> {
203    #[inline]
204    fn as_ref(&self) -> &std::path::Path {
205        std::path::Path::new(self)
206    }
207}
208
209impl alloc::borrow::Borrow<str> for KStringRef<'_> {
210    #[inline]
211    fn borrow(&self) -> &str {
212        self.as_str()
213    }
214}
215
216impl Default for KStringRef<'_> {
217    #[inline]
218    fn default() -> Self {
219        Self::new()
220    }
221}
222
223impl<'s, B: crate::backend::HeapStr> From<&'s KStringBase<B>> for KStringRef<'s> {
224    #[inline]
225    fn from(other: &'s KStringBase<B>) -> Self {
226        other.as_ref()
227    }
228}
229
230impl<'s, B: crate::backend::HeapStr> From<&'s KStringCowBase<'s, B>> for KStringRef<'s> {
231    #[inline]
232    fn from(other: &'s KStringCowBase<'s, B>) -> Self {
233        other.as_ref()
234    }
235}
236
237impl<'s> From<&'s StdString> for KStringRef<'s> {
238    #[inline]
239    fn from(other: &'s StdString) -> Self {
240        KStringRef::from_ref(other.as_str())
241    }
242}
243
244impl<'s> From<&'s BoxedStr> for KStringRef<'s> {
245    #[inline]
246    fn from(other: &'s BoxedStr) -> Self {
247        Self::from_ref(other)
248    }
249}
250
251impl<'s> From<&'s str> for KStringRef<'s> {
252    #[inline]
253    fn from(other: &'s str) -> Self {
254        KStringRef::from_ref(other)
255    }
256}
257
258#[cfg(feature = "serde")]
259impl serde::Serialize for KStringRef<'_> {
260    #[inline]
261    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
262    where
263        S: serde::Serializer,
264    {
265        serializer.serialize_str(self.as_str())
266    }
267}
268
269#[cfg(feature = "serde")]
270impl<'de: 's, 's> serde::Deserialize<'de> for KStringRef<'s> {
271    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
272    where
273        D: serde::Deserializer<'de>,
274    {
275        let s: &'s str = serde::Deserialize::deserialize(deserializer)?;
276        let s = KStringRef::from_ref(s);
277        Ok(s)
278    }
279}
280
281#[cfg(test)]
282mod test {
283    use super::*;
284
285    #[test]
286    fn test_size() {
287        println!("KStringRef: {}", size_of::<KStringRef<'static>>());
288    }
289}