docx_rs/documents/elements/
name.rs1use serde::{Serialize, Serializer};
2use std::io::Write;
3
4use std::str::FromStr;
5
6use crate::documents::BuildXML;
7use crate::{escape, xml_builder::*};
8
9#[derive(Debug, Clone, PartialEq)]
10pub struct Name {
11 name: String,
12}
13
14impl Name {
15 pub fn new(name: impl Into<String>) -> Name {
16 Name {
17 name: escape::escape(&name.into()),
18 }
19 }
20
21 pub fn starts_with(&self, s: &str) -> bool {
22 self.name.starts_with(s)
23 }
24
25 pub fn is_heading(&self) -> bool {
26 self.name.to_lowercase().starts_with("heading")
27 }
28
29 pub fn get_heading_number(&self) -> Option<usize> {
30 let replaced = self.name.to_lowercase().replace("heading ", "");
31 if let Ok(n) = usize::from_str(&replaced) {
32 Some(n)
33 } else {
34 None
35 }
36 }
37}
38
39impl BuildXML for Name {
40 fn build_to<W: Write>(
41 &self,
42 stream: xml::writer::EventWriter<W>,
43 ) -> xml::writer::Result<xml::writer::EventWriter<W>> {
44 XMLBuilder::from(stream).name(&self.name)?.into_inner()
45 }
46}
47
48impl Serialize for Name {
49 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
50 where
51 S: Serializer,
52 {
53 serializer.serialize_str(&self.name)
54 }
55}
56
57#[cfg(test)]
58mod tests {
59
60 use super::*;
61 #[cfg(test)]
62 use pretty_assertions::assert_eq;
63 use std::str;
64
65 #[test]
66 fn test_build() {
67 let c = Name::new("Heading");
68 let b = c.build();
69 assert_eq!(str::from_utf8(&b).unwrap(), r#"<w:name w:val="Heading" />"#);
70 }
71}