docx_rs/reader/
tab.rs

1use std::io::Read;
2use std::str::FromStr;
3
4use xml::attribute::OwnedAttribute;
5use xml::reader::{EventReader, XmlEvent};
6
7use crate::types::*;
8
9use super::*;
10
11fn read_custom_tab_stop_type(attributes: &[OwnedAttribute]) -> Result<TabValueType, ReaderError> {
12    for a in attributes {
13        let local_name = &a.name.local_name;
14        if local_name == "val" {
15            let v = a.value.to_owned();
16            if let Ok(t) = TabValueType::from_str(&v) {
17                return Ok(t);
18            }
19        }
20    }
21    Err(ReaderError::TypeError(crate::TypeError::FromStrError))
22}
23
24fn read_custom_tab_stop_leader(
25    attributes: &[OwnedAttribute],
26) -> Result<TabLeaderType, ReaderError> {
27    for a in attributes {
28        let local_name = &a.name.local_name;
29        if local_name == "leader" {
30            let v = a.value.to_owned();
31            if let Ok(t) = TabLeaderType::from_str(&v) {
32                return Ok(t);
33            }
34        }
35    }
36    Err(ReaderError::TypeError(crate::TypeError::FromStrError))
37}
38
39fn read_custom_tab_stop_pos(attributes: &[OwnedAttribute]) -> Result<f32, ReaderError> {
40    for a in attributes {
41        let local_name = &a.name.local_name;
42        if local_name == "pos" {
43            let v = a.value.to_owned();
44            if let Ok(t) = f32::from_str(&v) {
45                return Ok(t);
46            }
47        }
48    }
49    Err(ReaderError::TypeError(crate::TypeError::FromStrError))
50}
51
52impl ElementReader for Tab {
53    fn read<R: Read>(
54        r: &mut EventReader<R>,
55        attrs: &[OwnedAttribute],
56    ) -> Result<Self, ReaderError> {
57        let mut tab = Tab::new();
58        if let Ok(t) = read_custom_tab_stop_type(attrs) {
59            tab = tab.val(t);
60        }
61        if let Ok(pos) = read_custom_tab_stop_pos(attrs) {
62            tab = tab.pos(pos as usize);
63        }
64        if let Ok(leader) = read_custom_tab_stop_leader(attrs) {
65            tab = tab.leader(leader);
66        }
67        loop {
68            let e = r.next();
69            match e {
70                Ok(XmlEvent::EndElement { name, .. }) => {
71                    let e = XMLElement::from_str(&name.local_name).unwrap();
72                    if e == XMLElement::Tab {
73                        return Ok(tab);
74                    }
75                }
76                Err(_) => return Err(ReaderError::XMLReadError),
77                _ => {}
78            }
79        }
80    }
81}