1use alloc::{borrow::Cow, string::String, vec::Vec};
18
19#[derive(Clone, Debug)]
23pub struct IcalLeaf<'a>(pub Cow<'a, str>);
24
25impl<'a> IcalLeaf<'a> {
26 pub fn get(&self) -> &str {
28 &self.0
29 }
30
31 pub fn set(&mut self, text: impl Into<Cow<'a, str>>) {
33 self.0 = text.into();
34 }
35
36 pub(crate) fn into_static(self) -> IcalLeaf<'static> {
38 IcalLeaf(Cow::Owned(self.0.into_owned()))
39 }
40}
41
42impl<'a> From<&'a str> for IcalLeaf<'a> {
43 fn from(text: &'a str) -> Self {
44 Self(Cow::Borrowed(text))
45 }
46}
47
48impl From<String> for IcalLeaf<'_> {
49 fn from(text: String) -> Self {
50 Self(Cow::Owned(text))
51 }
52}
53
54#[derive(Clone, Debug)]
59pub struct IcalValueLeaf<'a>(pub Cow<'a, [u8]>);
60
61impl<'a> IcalValueLeaf<'a> {
62 pub fn as_bytes(&self) -> &[u8] {
64 &self.0
65 }
66
67 pub fn to_str_lossy(&self) -> Cow<'_, str> {
71 String::from_utf8_lossy(&self.0)
72 }
73
74 pub fn set(&mut self, bytes: impl Into<Cow<'a, [u8]>>) {
76 self.0 = bytes.into();
77 }
78
79 pub(crate) fn into_static(self) -> IcalValueLeaf<'static> {
81 IcalValueLeaf(Cow::Owned(self.0.into_owned()))
82 }
83}
84
85impl<'a> From<&'a [u8]> for IcalValueLeaf<'a> {
86 fn from(bytes: &'a [u8]) -> Self {
87 Self(Cow::Borrowed(bytes))
88 }
89}
90
91impl From<Vec<u8>> for IcalValueLeaf<'_> {
92 fn from(bytes: Vec<u8>) -> Self {
93 Self(Cow::Owned(bytes))
94 }
95}
96
97impl<'a> From<Cow<'a, str>> for IcalValueLeaf<'a> {
98 fn from(text: Cow<'a, str>) -> Self {
99 Self(match text {
100 Cow::Borrowed(text) => Cow::Borrowed(text.as_bytes()),
101 Cow::Owned(text) => Cow::Owned(text.into_bytes()),
102 })
103 }
104}
105
106#[cfg(test)]
107mod tests {
108 use alloc::vec::Vec;
109
110 use crate::tree::leaf::{IcalLeaf, IcalValueLeaf};
111
112 #[test]
113 fn replaces_leaf_contents() {
114 let mut text = IcalLeaf::from("a");
115 text.set("b");
116 assert_eq!(text.get(), "b");
117
118 let mut bytes = IcalValueLeaf::from(b"a".as_slice());
119 bytes.set(Vec::from(b"c".as_slice()));
120 assert_eq!(bytes.as_bytes(), b"c");
121 assert_eq!(bytes.to_str_lossy(), "c");
122 }
123}