Skip to main content

kstring/
string_cow.rs

1#[cfg(not(feature = "std"))]
2use alloc::boxed::Box;
3#[cfg(not(feature = "std"))]
4use alloc::string::String;
5use alloc::{borrow::Cow, fmt};
6
7use crate::KStringBase;
8use crate::KStringRef;
9use crate::KStringRefInner;
10
11type StdString = String;
12type BoxedStr = Box<str>;
13
14/// A reference to a UTF-8 encoded, immutable string.
15#[deprecated(
16    since = "2.0.4",
17    note = "for alternatives, see https://github.com/rosetta-rs/string-rosetta-rs"
18)]
19pub type KStringCow<'s> = KStringCowBase<'s, crate::backend::DefaultStr>;
20
21/// A reference to a UTF-8 encoded, immutable string.
22#[derive(Clone)]
23#[repr(transparent)]
24pub struct KStringCowBase<'s, B = crate::backend::DefaultStr> {
25    pub(crate) inner: KStringCowInner<'s, B>,
26}
27
28#[derive(Clone)]
29pub(crate) enum KStringCowInner<'s, B> {
30    Borrowed(&'s str),
31    Owned(KStringBase<B>),
32}
33
34impl<B> KStringCowBase<'_, B> {
35    /// Create a new empty `KStringCowBase`.
36    #[inline]
37    #[must_use]
38    pub const fn new() -> Self {
39        Self::from_static("")
40    }
41
42    /// Create a reference to a `'static` data.
43    #[inline]
44    #[must_use]
45    pub const fn from_static(other: &'static str) -> Self {
46        Self {
47            inner: KStringCowInner::Owned(KStringBase::from_static(other)),
48        }
49    }
50}
51
52impl<'s, B: crate::backend::HeapStr> KStringCowBase<'s, B> {
53    /// Create an owned `KStringCowBase`.
54    #[inline]
55    #[must_use]
56    pub fn from_boxed(other: BoxedStr) -> Self {
57        Self {
58            inner: KStringCowInner::Owned(KStringBase::from_boxed(other)),
59        }
60    }
61
62    /// Create an owned `KStringCowBase`.
63    #[inline]
64    #[must_use]
65    pub fn from_string(other: StdString) -> Self {
66        Self {
67            inner: KStringCowInner::Owned(KStringBase::from_string(other)),
68        }
69    }
70
71    /// Create a reference to a borrowed data.
72    #[inline]
73    #[must_use]
74    pub fn from_ref(other: &'s str) -> Self {
75        Self {
76            inner: KStringCowInner::Borrowed(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    /// Clone the data into an owned-type.
88    #[inline]
89    #[must_use]
90    pub fn into_owned(self) -> KStringBase<B> {
91        self.inner.into_owned()
92    }
93
94    /// Extracts a string slice containing the entire `KStringCowBase`.
95    #[inline]
96    #[must_use]
97    pub fn as_str(&self) -> &str {
98        self.inner.as_str()
99    }
100
101    /// Convert to a mutable string type, cloning the data if necessary.
102    #[inline]
103    #[must_use]
104    pub fn into_string(self) -> StdString {
105        String::from(self.into_boxed_str())
106    }
107
108    /// Convert to a mutable string type, cloning the data if necessary.
109    #[inline]
110    #[must_use]
111    pub fn into_boxed_str(self) -> BoxedStr {
112        self.inner.into_boxed_str()
113    }
114
115    /// Convert to a Cow str
116    #[inline]
117    #[must_use]
118    pub fn into_cow_str(self) -> Cow<'s, str> {
119        self.inner.into_cow_str()
120    }
121}
122
123impl<'s, B: crate::backend::HeapStr> KStringCowInner<'s, B> {
124    #[inline]
125    fn as_ref(&self) -> KStringRef<'_> {
126        match self {
127            Self::Borrowed(s) => KStringRef::from_ref(s),
128            Self::Owned(s) => s.as_ref(),
129        }
130    }
131
132    #[inline]
133    fn into_owned(self) -> KStringBase<B> {
134        match self {
135            Self::Borrowed(s) => KStringBase::from_ref(s),
136            Self::Owned(s) => s,
137        }
138    }
139
140    #[inline]
141    fn as_str(&self) -> &str {
142        match self {
143            Self::Borrowed(s) => s,
144            Self::Owned(s) => s.as_str(),
145        }
146    }
147
148    #[inline]
149    fn into_boxed_str(self) -> BoxedStr {
150        match self {
151            Self::Borrowed(s) => BoxedStr::from(s),
152            Self::Owned(s) => s.into_boxed_str(),
153        }
154    }
155
156    /// Convert to a Cow str
157    #[inline]
158    fn into_cow_str(self) -> Cow<'s, str> {
159        match self {
160            Self::Borrowed(s) => Cow::Borrowed(s),
161            Self::Owned(s) => s.into_cow_str(),
162        }
163    }
164}
165
166impl<B: crate::backend::HeapStr> core::ops::Deref for KStringCowBase<'_, B> {
167    type Target = str;
168
169    #[inline]
170    fn deref(&self) -> &str {
171        self.as_str()
172    }
173}
174
175impl<B: crate::backend::HeapStr> Eq for KStringCowBase<'_, B> {}
176
177impl<'s, B: crate::backend::HeapStr> PartialEq<Self> for KStringCowBase<'s, B> {
178    #[inline]
179    fn eq(&self, other: &Self) -> bool {
180        PartialEq::eq(self.as_str(), other.as_str())
181    }
182}
183
184impl<B: crate::backend::HeapStr> PartialEq<str> for KStringCowBase<'_, B> {
185    #[inline]
186    fn eq(&self, other: &str) -> bool {
187        PartialEq::eq(self.as_str(), other)
188    }
189}
190
191impl<'s, B: crate::backend::HeapStr> PartialEq<&'s str> for KStringCowBase<'s, B> {
192    #[inline]
193    fn eq(&self, other: &&str) -> bool {
194        PartialEq::eq(self.as_str(), *other)
195    }
196}
197
198impl<B: crate::backend::HeapStr> PartialEq<String> for KStringCowBase<'_, B> {
199    #[inline]
200    fn eq(&self, other: &StdString) -> bool {
201        PartialEq::eq(self.as_str(), other.as_str())
202    }
203}
204
205impl<B: crate::backend::HeapStr> Ord for KStringCowBase<'_, B> {
206    #[inline]
207    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
208        self.as_str().cmp(other.as_str())
209    }
210}
211
212impl<B: crate::backend::HeapStr> PartialOrd for KStringCowBase<'_, B> {
213    #[inline]
214    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
215        Some(self.cmp(other))
216    }
217}
218
219impl<B: crate::backend::HeapStr> core::hash::Hash for KStringCowBase<'_, B> {
220    #[inline]
221    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
222        self.as_str().hash(state);
223    }
224}
225
226impl<B: crate::backend::HeapStr> fmt::Debug for KStringCowBase<'_, B> {
227    #[inline]
228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229        self.as_str().fmt(f)
230    }
231}
232
233impl<B: crate::backend::HeapStr> fmt::Display for KStringCowBase<'_, B> {
234    #[inline]
235    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236        fmt::Display::fmt(self.as_str(), f)
237    }
238}
239
240impl<B: crate::backend::HeapStr> AsRef<str> for KStringCowBase<'_, B> {
241    #[inline]
242    fn as_ref(&self) -> &str {
243        self.as_str()
244    }
245}
246
247impl<B: crate::backend::HeapStr> AsRef<[u8]> for KStringCowBase<'_, B> {
248    #[inline]
249    fn as_ref(&self) -> &[u8] {
250        self.as_bytes()
251    }
252}
253
254#[cfg(feature = "std")]
255impl<B: crate::backend::HeapStr> AsRef<std::ffi::OsStr> for KStringCowBase<'_, B> {
256    #[inline]
257    fn as_ref(&self) -> &std::ffi::OsStr {
258        (**self).as_ref()
259    }
260}
261
262#[cfg(feature = "std")]
263impl<B: crate::backend::HeapStr> AsRef<std::path::Path> for KStringCowBase<'_, B> {
264    #[inline]
265    fn as_ref(&self) -> &std::path::Path {
266        std::path::Path::new(self)
267    }
268}
269
270impl<B: crate::backend::HeapStr> core::borrow::Borrow<str> for KStringCowBase<'_, B> {
271    #[inline]
272    fn borrow(&self) -> &str {
273        self.as_str()
274    }
275}
276
277impl<B> Default for KStringCowBase<'_, B> {
278    #[inline]
279    fn default() -> Self {
280        Self::new()
281    }
282}
283
284impl<B: crate::backend::HeapStr> From<KStringBase<B>> for KStringCowBase<'_, B> {
285    #[inline]
286    fn from(other: KStringBase<B>) -> Self {
287        let inner = KStringCowInner::Owned(other);
288        Self { inner }
289    }
290}
291
292impl<'s, B: crate::backend::HeapStr> From<&'s KStringBase<B>> for KStringCowBase<'s, B> {
293    #[inline]
294    fn from(other: &'s KStringBase<B>) -> Self {
295        let other = other.as_ref();
296        other.into()
297    }
298}
299
300impl<'s, B: crate::backend::HeapStr> From<KStringRef<'s>> for KStringCowBase<'s, B> {
301    #[inline]
302    fn from(other: KStringRef<'s>) -> Self {
303        match other.inner {
304            KStringRefInner::Borrowed(s) => Self::from_ref(s),
305            KStringRefInner::Singleton(s) => Self::from_static(s),
306        }
307    }
308}
309
310impl<'s, B: crate::backend::HeapStr> From<&'s KStringRef<'s>> for KStringCowBase<'s, B> {
311    #[inline]
312    fn from(other: &'s KStringRef<'s>) -> Self {
313        match other.inner {
314            KStringRefInner::Borrowed(s) => Self::from_ref(s),
315            KStringRefInner::Singleton(s) => Self::from_static(s),
316        }
317    }
318}
319
320impl<B: crate::backend::HeapStr> From<StdString> for KStringCowBase<'_, B> {
321    #[inline]
322    fn from(other: StdString) -> Self {
323        Self::from_string(other)
324    }
325}
326
327impl<'s, B: crate::backend::HeapStr> From<&'s StdString> for KStringCowBase<'s, B> {
328    #[inline]
329    fn from(other: &'s StdString) -> Self {
330        Self::from_ref(other.as_str())
331    }
332}
333
334impl<B: crate::backend::HeapStr> From<BoxedStr> for KStringCowBase<'_, B> {
335    #[inline]
336    fn from(other: BoxedStr) -> Self {
337        // Since the memory is already allocated, don't bother moving it into a FixedString
338        Self::from_boxed(other)
339    }
340}
341
342impl<'s, B: crate::backend::HeapStr> From<&'s BoxedStr> for KStringCowBase<'s, B> {
343    #[inline]
344    fn from(other: &'s BoxedStr) -> Self {
345        Self::from_ref(other)
346    }
347}
348
349impl<'s, B: crate::backend::HeapStr> From<&'s str> for KStringCowBase<'s, B> {
350    #[inline]
351    fn from(other: &'s str) -> Self {
352        Self::from_ref(other)
353    }
354}
355
356impl<B: crate::backend::HeapStr> core::str::FromStr for KStringCowBase<'_, B> {
357    type Err = core::convert::Infallible;
358    #[inline]
359    fn from_str(s: &str) -> Result<Self, Self::Err> {
360        Ok(Self::from_string(s.into()))
361    }
362}
363
364#[cfg(feature = "serde")]
365impl<B: crate::backend::HeapStr> serde::Serialize for KStringCowBase<'_, B> {
366    #[inline]
367    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
368    where
369        S: serde::Serializer,
370    {
371        serializer.serialize_str(self.as_str())
372    }
373}
374
375#[cfg(feature = "serde")]
376impl<'de, B: crate::backend::HeapStr> serde::Deserialize<'de> for KStringCowBase<'_, B> {
377    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
378    where
379        D: serde::Deserializer<'de>,
380    {
381        KStringBase::deserialize(deserializer).map(|s| s.into())
382    }
383}
384
385#[cfg(test)]
386mod test {
387    use super::*;
388
389    #[test]
390    fn test_size() {
391        println!("KStringCow: {}", size_of::<KStringCow<'static>>());
392    }
393}