use super::escape;
use crate::read_write::component::Component;
use super::component::error::ComponentParseError;
use std::fmt;
use std::str::FromStr;
#[derive(Clone, Default, Debug, Eq, PartialEq)]
pub struct VCard(pub Vec<Component>);
impl VCard {
#[must_use]
pub fn new(vec: Vec<Component>) -> Self {
Self(vec)
}
pub fn from_str_to_vec(s: &str) -> Result<Vec<Self>, ComponentParseError> {
let split = s.split_inclusive("\r\nEND:VCARD\r\n");
let mut vec = Vec::new();
for split in split {
vec.push(split.parse()?);
}
Ok(vec)
}
#[must_use]
pub fn from_slice_to_string(v: &[Self]) -> String {
let mut string = String::new();
for item in v {
string.push_str(&item.to_string());
string.push_str("\r\n");
string.push_str("\r\n");
}
string
}
}
impl fmt::Display for VCard {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "BEGIN:VCARD\r\nVERSION:4.0\r\n")?;
for comp in &self.0 {
comp.fmt(f)?;
}
write!(f, "END:VCARD\r\n")
}
}
impl FromStr for VCard {
type Err = super::component::error::ComponentParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let unfolded = escape::unfold_line(s);
let mut components: Vec<Component> = Vec::new();
for line in unfolded.lines() {
if !line.is_empty() {
components.push(line.parse()?);
}
}
components.retain(|x| {
x.name != "VERSION" && x.name != "BEGIN" && x.name != "END"
});
Ok(Self(components))
}
}