use alloc::borrow::Cow;
use alloc::string::String;
use alloc::vec::Vec;
use core::str::FromStr;
use super::Tag;
use super::error::Error;
use crate::filter::SingleLetterTag;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CowTag<'a> {
buf: Vec<Cow<'a, str>>,
}
impl<'a> CowTag<'a> {
pub fn parse(tag: Vec<Cow<'a, str>>) -> Result<Self, Error> {
if tag.is_empty() {
return Err(Error::EmptyTag);
}
Ok(Self { buf: tag })
}
#[inline]
pub fn kind(&self) -> &str {
self.buf[0].as_ref()
}
#[inline]
pub fn content(&self) -> Option<&str> {
self.buf.get(1).map(|s| s.as_ref())
}
pub fn extract(&self) -> Option<(SingleLetterTag, &str)> {
if self.buf.len() >= 2 {
let tag_name: SingleLetterTag = SingleLetterTag::from_str(&self.buf[0]).ok()?;
let tag_value: &str = &self.buf[1];
Some((tag_name, tag_value))
} else {
None
}
}
pub fn into_owned(self) -> Tag {
let buf: Vec<String> = self.buf.into_iter().map(|t| t.into_owned()).collect();
Tag::new(buf)
}
#[inline]
pub fn into_inner(self) -> Vec<Cow<'a, str>> {
self.buf
}
}
impl<'a> From<&'a Tag> for CowTag<'a> {
fn from(tag: &'a Tag) -> Self {
Self {
buf: tag.buf.iter().map(|v| Cow::Borrowed(v.as_str())).collect(),
}
}
}