docx_reader/reader/
tab.rs

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