BlueGit

timfa posprint

Files

posprint / src / params.rs

params.rs

params.rs 6.0 KiB Download Raw
1use std::collections::BTreeSet;
2
3use crate::dsl::{Document, Inline};
4
5pub fn collect_parameter_names(document: &Document) -> Vec<String> {
6 let mut names = BTreeSet::new();
7 for block in &document.blocks {
8 collect_from_block(block, &mut names);
9 }
10 names.into_iter().collect()
11}
12
13pub fn collect_parameter_names_from_source(source: &str) -> Result<Vec<String>, crate::dsl::ParseError> {
14 let doc = crate::dsl::parse(source)?;
15 Ok(collect_parameter_names(&doc))
16}
17
18pub fn substitute_inlines(inlines: &[Inline], values: &std::collections::HashMap<String, String>) -> Vec<Inline> {
19 inlines
20 .iter()
21 .map(|inline| match inline {
22 Inline::Text(t) => Inline::Text(t.clone()),
23 Inline::Code(t) => Inline::Code(t.clone()),
24 Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
25 Inline::Bold(inner) => Inline::Bold(substitute_inlines(inner, values)),
26 Inline::Italic(inner) => Inline::Italic(substitute_inlines(inner, values)),
27 })
28 .collect()
29}
30
31pub fn substitute_string(input: &str, values: &std::collections::HashMap<String, String>) -> String {
32 let mut out = String::new();
33 let chars: Vec<char> = input.chars().collect();
34 let mut i = 0;
35 while i < chars.len() {
36 if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
37 let start = i + 2;
38 let mut j = start;
39 while j < chars.len() && chars[j] != '}' {
40 j += 1;
41 }
42 if j < chars.len() {
43 let name: String = chars[start..j].iter().collect();
44 out.push_str(values.get(&name).map(String::as_str).unwrap_or(""));
45 i = j + 1;
46 continue;
47 }
48 }
49 out.push(chars[i]);
50 i += 1;
51 }
52 out
53}
54
55pub fn substitute_document(
56 document: &Document,
57 values: &std::collections::HashMap<String, String>,
58) -> Document {
59 use crate::dsl::Block;
60
61 let blocks = document
62 .blocks
63 .iter()
64 .map(|block| match block {
65 Block::Paragraph { align, inlines } => Block::Paragraph {
66 align: *align,
67 inlines: substitute_inlines(inlines, values),
68 },
69 Block::Heading { level, inlines } => Block::Heading {
70 level: *level,
71 inlines: substitute_inlines(inlines, values),
72 },
73 Block::Rule => Block::Rule,
74 Block::Feed(n) => Block::Feed(*n),
75 Block::Cut => Block::Cut,
76 Block::Image { path, width, align } => Block::Image {
77 path: substitute_string(path, values),
78 width: *width,
79 align: *align,
80 },
81 Block::Barcode {
82 symbology,
83 data,
84 height,
85 align,
86 show_text,
87 } => Block::Barcode {
88 symbology: *symbology,
89 data: substitute_string(data, values),
90 height: *height,
91 align: *align,
92 show_text: *show_text,
93 },
94 Block::Qr {
95 data,
96 size,
97 ecc,
98 align,
99 } => Block::Qr {
100 data: substitute_string(data, values),
101 size: *size,
102 ecc: *ecc,
103 align: *align,
104 },
105 })
106 .collect();
107 Document { blocks }
108}
109
110fn collect_from_block(block: &crate::dsl::Block, names: &mut BTreeSet<String>) {
111 use crate::dsl::Block;
112
113 match block {
114 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
115 collect_from_inlines(inlines, names);
116 }
117 Block::Image { path, .. } => collect_from_raw(path, names),
118 Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_from_raw(data, names),
119 Block::Rule | Block::Feed(_) | Block::Cut => {}
120 }
121}
122
123fn collect_from_inlines(inlines: &[Inline], names: &mut BTreeSet<String>) {
124 for inline in inlines {
125 match inline {
126 Inline::Param(name) => {
127 names.insert(name.clone());
128 }
129 Inline::Bold(inner) | Inline::Italic(inner) => collect_from_inlines(inner, names),
130 Inline::Text(_) | Inline::Code(_) => {}
131 }
132 }
133}
134
135fn collect_from_raw(text: &str, names: &mut BTreeSet<String>) {
136 let chars: Vec<char> = text.chars().collect();
137 let mut i = 0;
138 while i < chars.len() {
139 if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
140 let start = i + 2;
141 let mut j = start;
142 while j < chars.len() && chars[j] != '}' {
143 j += 1;
144 }
145 if j < chars.len() {
146 let name: String = chars[start..j].iter().collect();
147 names.insert(name);
148 i = j + 1;
149 continue;
150 }
151 }
152 i += 1;
153 }
154}
155
156#[cfg(test)]
157mod tests {
158 use super::*;
159 use std::collections::HashMap;
160
161 #[test]
162 fn collects_unique_sorted_names() {
163 let doc = crate::dsl::parse("${B}\n${A}\n${B}").unwrap();
164 assert_eq!(collect_parameter_names(&doc), vec!["A", "B"]);
165 }
166
167 #[test]
168 fn substitutes_all_occurrences() {
169 let doc = crate::dsl::parse("Hi ${Name} and ${Name}").unwrap();
170 let mut values = HashMap::new();
171 values.insert("Name".into(), "Ada".into());
172 let sub = substitute_document(&doc, &values);
173 let crate::dsl::Block::Paragraph { inlines, .. } = &sub.blocks[0] else {
174 panic!();
175 };
176 assert!(matches!(
177 inlines.as_slice(),
178 [
179 Inline::Text(a),
180 Inline::Text(b),
181 Inline::Text(c),
182 Inline::Text(d),
183 ] if a == "Hi " && b == "Ada" && c == " and " && d == "Ada"
184 ));
185 }
186}