einfach_xml_builder/
declaration.rs

1/// Represents an XML declaration.
2pub struct Declaration<'a> {
3    /// The XML version.
4    version: &'a str,
5    /// The encoding used for the XML document.
6    encoding: &'a str,
7    /// The standalone status of the XML document (optional).
8    standalone: Option<bool>,
9}
10
11impl<'a> Declaration<'a> {
12    /// Creates a new instance of `Declaration` with the given version and encoding.
13    ///
14    /// # Arguments
15    ///
16    /// * `version` - The XML version.
17    /// * `encoding` - The encoding used for the XML document.
18    ///
19    /// # Example
20    ///
21    /// ```
22    /// let declaration = Declaration::new("1.0", "UTF-8");
23    /// ```
24    pub fn new(version: &'a str, encoding: &'a str) -> Self {
25        Declaration {
26            version,
27            encoding,
28            standalone: None,
29        }
30    }
31
32    /// Sets the standalone status of the XML document and returns a modified `Declaration`.
33    ///
34    /// # Arguments
35    ///
36    /// * `standalone` - The standalone status of the XML document.
37    ///
38    /// # Example
39    ///
40    /// ```
41    /// let declaration = Declaration::new("1.0", "UTF-8")
42    ///     .with_standalone(true);
43    /// ```
44    pub fn with_standalone(mut self, standalone: bool) -> Self {
45        self.standalone = Some(standalone);
46        self
47    }
48}
49
50impl<'a> std::fmt::Display for Declaration<'a> {
51    /// Formats the declaration as an XML declaration string.
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        write!(
54            f,
55            r#"<?xml version="{}" encoding="{}""#,
56            self.version, self.encoding
57        )?;
58
59        if let Some(standalone) = self.standalone {
60            let standalone_as_string = if standalone {
61                "yes"
62            }
63            else {
64                "no"
65            };
66
67            write!(f, r#" standalone="{}""#, standalone_as_string)?;
68        }
69
70        write!(f, "?>")?;
71        Ok(())
72    }
73}