use std::fmt;
use crate::escape::{AttributeEscapes, Escaped};
use crate::name::{Name, OwnedName};
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Attribute<'a> {
pub name: Name<'a>,
pub value: &'a str,
}
impl<'a> fmt::Display for Attribute<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}=\"{}\"", self.name, Escaped::<AttributeEscapes>::new(self.value))
}
}
impl<'a> Attribute<'a> {
#[inline]
#[must_use]
pub fn to_owned(&self) -> OwnedAttribute {
OwnedAttribute {
name: self.name.into(),
value: self.value.into(),
}
}
#[inline]
#[must_use]
pub fn new(name: Name<'a>, value: &'a str) -> Attribute<'a> {
Attribute { name, value }
}
}
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct OwnedAttribute {
pub name: OwnedName,
pub value: String,
}
impl OwnedAttribute {
#[must_use]
#[inline]
pub fn borrow(&self) -> Attribute<'_> {
Attribute {
name: self.name.borrow(),
value: &self.value,
}
}
#[inline]
pub fn new<S: Into<String>>(name: OwnedName, value: S) -> OwnedAttribute {
OwnedAttribute {
name,
value: value.into(),
}
}
}
impl fmt::Display for OwnedAttribute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}=\"{}\"", self.name, Escaped::<AttributeEscapes>::new(&self.value))
}
}
#[cfg(test)]
mod tests {
use super::Attribute;
use crate::name::Name;
#[test]
fn attribute_display() {
let attr = Attribute::new(
Name::qualified("attribute", "urn:namespace", Some("n")),
"its value with > & \" ' < weird symbols",
);
assert_eq!(
&*attr.to_string(),
"{urn:namespace}n:attribute=\"its value with > & " ' < weird symbols\""
);
}
}