hml_rs/names/
attribute.rs

1//a Imports
2use super::{Name, NamespaceStack};
3use crate::MarkupResult;
4
5//a Attribute
6//tp Attribute
7/// An [Attribute] has a [Name] and a [String] value.
8///
9/// They correspond to attributes in markup tags
10#[derive(Clone, Eq, PartialEq, Hash, Debug)]
11pub struct Attribute {
12    /// Name and optional namespace
13    pub name: Name,
14
15    /// Attribute value.
16    pub value: String,
17}
18
19impl Attribute {
20    //fp new
21    /// Create a new [Attribute] using the [NamespaceStack] to resolve the name
22    pub fn new(
23        ns_stack: &mut NamespaceStack,
24        prefix: &str,
25        name: &str,
26        value: String,
27    ) -> MarkupResult<Self> {
28        if ns_stack.uses_xmlns() {
29            if prefix.is_empty() && name == "xmlns" {
30                println!("Add ns '' to be {}", value);
31                ns_stack.add_ns("", &value);
32                let name = Name::new(ns_stack, name, name)?;
33                return Ok(Self { name, value });
34            } else if prefix == "xmlns" {
35                println!("Add ns {} to be value {}", name, value);
36                ns_stack.add_ns(name, &value);
37            }
38        }
39        let name = Name::new(ns_stack, prefix, name)?;
40        Ok(Self { name, value })
41    }
42
43    //zz All done
44}
45
46//a Attributes
47//tp Attributes
48/// A list of attributes in the order in which they appear in the
49/// markup stream
50#[derive(Debug, Default)]
51pub struct Attributes {
52    //
53    attributes: Vec<Attribute>,
54}
55
56//ip Attributes
57impl Attributes {
58    //mp is_empty
59    /// Returns true if the [Attributes] list is empty
60    pub fn is_empty(&self) -> bool {
61        self.attributes.is_empty()
62    }
63
64    //mp add
65    /// Add a prefix/name and value to the [Attributes] list, using
66    /// the [NamespaceStack] to resolve the prefix into a URI
67    pub fn add(
68        &mut self,
69        ns_stack: &mut NamespaceStack,
70        prefix: &str,
71        name: &str,
72        value: String,
73    ) -> MarkupResult<()> {
74        self.attributes
75            .push(Attribute::new(ns_stack, prefix, name, value)?);
76        Ok(())
77    }
78
79    //mp steal
80    /// Take all the attributes away from another [Attributes] and add them to this
81    pub fn steal(&mut self, v: &mut Self) {
82        self.attributes.append(&mut v.attributes);
83    }
84
85    //mp take
86    /// Deconstruct this list of [Attribute] to a `Vec<Attribute>`
87    pub fn take(self) -> Vec<Attribute> {
88        self.attributes
89    }
90
91    //ap attributes
92    /// Borrow the [Attribute] vec
93    pub fn attributes(&self) -> &[Attribute] {
94        &self.attributes
95    }
96
97    //zz All done
98}