docx_reader/documents/elements/
instr_tc.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use serde::Serialize;

use crate::documents::*;

// https://c-rex.net/projects/samples/ooxml/e1/Part4/OOXML_P4_DOCX_TCTC_topic_ID0EU2N1.html
#[derive(Serialize, Debug, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct InstrTC {
	pub text: String,
	// \n Omits the page number for the entry.
	pub omits_page_number: bool,
	pub level: Option<usize>,
	// \f
	pub item_type_identifier: Option<String>,
}

impl InstrTC {
	pub fn new(text: impl Into<String>) -> Self {
		Self {
			text: text.into(),
			..Default::default()
		}
	}

	pub fn omits_page_number(mut self) -> Self {
		self.omits_page_number = true;
		self
	}

	pub fn level(mut self, level: usize) -> Self {
		self.level = Some(level);
		self
	}

	pub fn item_type_identifier(mut self, t: impl Into<String>) -> Self {
		self.item_type_identifier = Some(t.into());
		self
	}
}

fn parse_level(i: &str) -> Option<usize> {
	let r = i.replace("&quot;", "").replace("\"", "");
	if let Ok(l) = usize::from_str(&r) {
		return Some(l);
	}
	None
}

impl std::str::FromStr for InstrTC {
	type Err = ();

	fn from_str(instr: &str) -> Result<Self, Self::Err> {
		let mut s = instr.split(' ');
		let text = s.next();
		let mut tc = InstrTC::new(text.unwrap_or_default());
		loop {
			if let Some(i) = s.next() {
				match i {
					"\\f" => {
						if let Some(r) = s.next() {
							let r = r.replace("&quot;", "").replace("\"", "");
							tc = tc.item_type_identifier(r);
						}
					}
					"\\l" => {
						if let Some(r) = s.next() {
							if let Some(l) = parse_level(r) {
								tc = tc.level(l);
							}
						}
					}
					"\\n" => tc = tc.omits_page_number(),
					_ => {}
				}
			} else {
				return Ok(tc);
			}
		}
	}
}