mathml_core/traits/
mod.rs

1use std::{
2    collections::BTreeMap,
3    fmt::{Display, Formatter},
4};
5
6/// A trait for all MathML elements.
7pub trait MathElement
8where
9    Self: Clone + Display,
10{
11    /// Get the tag name of the element.
12    fn tag_name(&self) -> &'static str;
13    /// Get all attributes directly
14    fn get_attributes(&self) -> &BTreeMap<String, String>;
15    /// Modify all attributes directly
16    fn mut_attributes(&mut self) -> &mut BTreeMap<String, String>;
17    /// Add an attribute to the operator.
18    fn add_attribute<K, V>(&mut self, key: K, value: V)
19    where
20        K: ToString,
21        V: ToString,
22    {
23        self.mut_attributes().insert(key.to_string(), value.to_string());
24    }
25    /// Add an attribute to the operator.
26    fn with_attribute<K, V>(mut self, key: K, value: V) -> Self
27    where
28        K: ToString,
29        V: ToString,
30    {
31        self.add_attribute(key, value);
32        self
33    }
34}
35
36pub(crate) fn write_tag_start<T>(f: &mut Formatter<'_>, element: &T) -> std::fmt::Result
37where
38    T: MathElement,
39{
40    write!(f, "<{}", element.tag_name())?;
41    for (key, value) in element.get_attributes() {
42        write!(f, " {}=\"{}\"", key, value)?;
43    }
44    f.write_str(">")
45}
46
47pub(crate) fn write_tag_close<T>(f: &mut Formatter<'_>, element: &T) -> std::fmt::Result
48where
49    T: MathElement,
50{
51    write!(f, "</{}>", element.tag_name())
52}
53
54pub(crate) fn write_tag_self_close<T>(f: &mut Formatter<'_>, element: &T) -> std::fmt::Result
55where
56    T: MathElement,
57{
58    write!(f, "<{}", element.tag_name())?;
59    for (key, value) in element.get_attributes() {
60        write!(f, " {}=\"{}\"", key, value)?;
61    }
62    f.write_str("/>")
63}