|
| 1 | +#![cfg(feature = "alloc")] |
| 2 | + |
| 3 | +extern crate alloc; |
| 4 | + |
| 5 | +use crate::len_type::LenType; |
| 6 | +use crate::{CapacityError, String, StringView}; |
| 7 | +use core::borrow::Borrow; |
| 8 | + |
| 9 | +/// A clone-on-write string type for heapless |
| 10 | +#[derive(Debug)] |
| 11 | +pub enum Cow<'a, const N: usize, LenT: LenType = usize> { |
| 12 | + Borrowed(&'a StringView<LenT>), |
| 13 | + Owned(String<N, LenT>), |
| 14 | +} |
| 15 | + |
| 16 | +impl<'a, const N: usize, LenT: LenType> Cow<'a, N, LenT> { |
| 17 | + pub fn to_owned(&self) -> String<N, LenT> { |
| 18 | + match self { |
| 19 | + Cow::Borrowed(sv) => String::from(sv), |
| 20 | + Cow::Owned(s) => s.clone(), |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + pub fn as_str(&self) -> &str { |
| 25 | + match self { |
| 26 | + Cow::Borrowed(sv) => sv.as_str(), |
| 27 | + Cow::Owned(s) => s.as_str(), |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + pub fn is_borrowed(&self) -> bool { |
| 32 | + matches!(self, Cow::Borrowed(_)) |
| 33 | + } |
| 34 | + |
| 35 | + pub fn is_owned(&self) -> bool { |
| 36 | + matches!(self, Cow::Owned(_)) |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +impl<'a, const N: usize, LenT: LenType> From<&'a StringView<LenT>> for Cow<'a, N, LenT> { |
| 41 | + fn from(sv: &'a StringView<LenT>) -> Self { |
| 42 | + Cow::Borrowed(sv) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +impl<const N: usize, LenT: LenType> From<String<N, LenT>> for Cow<'_, N, LenT> { |
| 47 | + fn from(s: String<N, LenT>) -> Self { |
| 48 | + Cow::Owned(s) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +impl<'a, const N: usize, LenT: LenType> Borrow<str> for Cow<'a, N, LenT> { |
| 53 | + fn borrow(&self) -> &str { |
| 54 | + self.as_str() |
| 55 | + } |
| 56 | +} |
0 commit comments