use alloc::{borrow::Cow, string::String, vec::Vec};
#[derive(Clone, Debug)]
pub struct VcardLeaf<'a>(pub Cow<'a, str>);
impl<'a> VcardLeaf<'a> {
pub fn get(&self) -> &str {
&self.0
}
pub fn set(&mut self, text: impl Into<Cow<'a, str>>) {
self.0 = text.into();
}
pub(crate) fn into_static(self) -> VcardLeaf<'static> {
VcardLeaf(Cow::Owned(self.0.into_owned()))
}
}
impl<'a> From<&'a str> for VcardLeaf<'a> {
fn from(text: &'a str) -> Self {
Self(Cow::Borrowed(text))
}
}
impl From<String> for VcardLeaf<'_> {
fn from(text: String) -> Self {
Self(Cow::Owned(text))
}
}
#[derive(Clone, Debug)]
pub struct VcardValueLeaf<'a>(pub Cow<'a, [u8]>);
impl<'a> VcardValueLeaf<'a> {
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
pub fn to_str_lossy(&self) -> Cow<'_, str> {
String::from_utf8_lossy(&self.0)
}
pub fn set(&mut self, bytes: impl Into<Cow<'a, [u8]>>) {
self.0 = bytes.into();
}
pub(crate) fn into_static(self) -> VcardValueLeaf<'static> {
VcardValueLeaf(Cow::Owned(self.0.into_owned()))
}
}
impl<'a> From<&'a [u8]> for VcardValueLeaf<'a> {
fn from(bytes: &'a [u8]) -> Self {
Self(Cow::Borrowed(bytes))
}
}
impl From<Vec<u8>> for VcardValueLeaf<'_> {
fn from(bytes: Vec<u8>) -> Self {
Self(Cow::Owned(bytes))
}
}
impl<'a> From<Cow<'a, str>> for VcardValueLeaf<'a> {
fn from(text: Cow<'a, str>) -> Self {
Self(match text {
Cow::Borrowed(text) => Cow::Borrowed(text.as_bytes()),
Cow::Owned(text) => Cow::Owned(text.into_bytes()),
})
}
}
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use crate::tree::leaf::{VcardLeaf, VcardValueLeaf};
#[test]
fn replaces_leaf_contents() {
let mut text = VcardLeaf::from("a");
text.set("b");
assert_eq!(text.get(), "b");
let mut bytes = VcardValueLeaf::from(b"a".as_slice());
bytes.set(Vec::from(b"c".as_slice()));
assert_eq!(bytes.as_bytes(), b"c");
assert_eq!(bytes.to_str_lossy(), "c");
}
}