-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
xmlwriter.rs
445 lines (368 loc) · 13.3 KB
/
xmlwriter.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// xmlwriter - a module for writing XML in the same format and with the same
// escaping as used by Excel in xlsx xml files. This is a base "class" or set of
// functionality for all of the other xml writing structs.
//
// SPDX-License-Identifier: MIT OR Apache-2.0 Copyright 2022, John McNamara,
// jmcnamara@cpan.org
use std::borrow::Cow;
use std::fs::File;
use std::io::{BufWriter, Read, Seek, Write};
use regex::Regex;
use tempfile::tempfile;
pub struct XMLWriter {
pub(crate) xmlfile: BufWriter<File>,
}
impl Default for XMLWriter {
fn default() -> Self {
Self::new()
}
}
impl XMLWriter {
// Create a new XMLWriter struct to write XML to a given filehandle.
pub(crate) fn new() -> XMLWriter {
let xmlfile = tempfile().unwrap();
let xmlfile = BufWriter::new(xmlfile);
XMLWriter { xmlfile }
}
// Helper function for tests to read xml data back from the xml filehandle.
#[allow(dead_code)]
pub(crate) fn read_to_string(&mut self) -> String {
let mut xml_string = String::new();
self.xmlfile.rewind().unwrap();
self.xmlfile
.get_ref()
.read_to_string(&mut xml_string)
.unwrap();
xml_string
}
// Return data to write to xlsx/zip file member.
pub(crate) fn read_to_buffer(&mut self) -> Vec<u8> {
let mut buffer = Vec::new();
self.xmlfile.rewind().unwrap();
self.xmlfile.get_ref().read_to_end(&mut buffer).unwrap();
buffer
}
// Return data to write to xlsx/zip file member.
pub(crate) fn reset(&mut self) {
self.xmlfile.rewind().unwrap();
self.xmlfile.get_ref().set_len(0).unwrap();
}
// Write an XML file declaration.
pub(crate) fn xml_declaration(&mut self) {
writeln!(
&mut self.xmlfile,
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>"#
)
.expect("Couldn't write to file");
}
// Write an XML start tag without attributes.
pub(crate) fn xml_start_tag(&mut self, tag: &str) {
write!(&mut self.xmlfile, r"<{}>", tag).expect("Couldn't write to file");
}
// Write an XML start tag with attributes.
pub(crate) fn xml_start_tag_attr(&mut self, tag: &str, attributes: &Vec<(&str, String)>) {
let mut attribute_str = "".to_string();
for attribute in attributes {
let pair = format!(r#" {}="{}""#, attribute.0, escape_attributes(&attribute.1));
attribute_str.push_str(&pair);
}
write!(&mut self.xmlfile, r"<{}{}>", tag, attribute_str).expect("Couldn't write to file");
}
// Write an XML end tag.
pub(crate) fn xml_end_tag(&mut self, tag: &str) {
write!(&mut self.xmlfile, r"</{}>", tag).expect("Couldn't write to file");
}
// Write an empty XML tag without attributes.
pub(crate) fn xml_empty_tag(&mut self, tag: &str) {
write!(&mut self.xmlfile, r"<{}/>", tag).expect("Couldn't write to file");
}
// Write an empty XML tag with attributes.
pub(crate) fn xml_empty_tag_attr(&mut self, tag: &str, attributes: &Vec<(&str, String)>) {
let mut attribute_str = "".to_string();
for attribute in attributes {
let pair = format!(r#" {}="{}""#, attribute.0, escape_attributes(&attribute.1));
attribute_str.push_str(&pair);
}
write!(&mut self.xmlfile, r"<{}{}/>", tag, attribute_str).expect("Couldn't write to file");
}
// Write an XML element containing data without attributes.
pub(crate) fn xml_data_element(&mut self, tag: &str, data: &str) {
write!(
&mut self.xmlfile,
r"<{}>{}</{}>",
tag,
escape_data(data),
tag
)
.expect("Couldn't write to file");
}
// Write an XML element containing data with attributes.
pub(crate) fn xml_data_element_attr(
&mut self,
tag: &str,
data: &str,
attributes: &Vec<(&str, String)>,
) {
let mut attribute_str = "".to_string();
for attribute in attributes {
let pair = format!(r#" {}="{}""#, attribute.0, escape_attributes(&attribute.1));
attribute_str.push_str(&pair);
}
write!(
&mut self.xmlfile,
r"<{}{}>{}</{}>",
tag,
attribute_str,
escape_data(data),
tag
)
.expect("Couldn't write to file");
}
// Optimized tag writer for shared strings `<si>` elements.
pub(crate) fn xml_si_element(&mut self, string: &str, preserve_whitespace: bool) {
if preserve_whitespace {
write!(
&mut self.xmlfile,
r#"<si><t xml:space="preserve">{}</t></si>"#,
escape_si_data(&escape_xml_escapes(string))
)
.expect("Couldn't write to file");
} else {
write!(
&mut self.xmlfile,
"<si><t>{}</t></si>",
escape_si_data(&escape_xml_escapes(string))
)
.expect("Couldn't write to file");
}
}
// Write the theme string to the theme file.
pub(crate) fn write_theme(&mut self, theme: &str) {
writeln!(&mut self.xmlfile, "{}", theme).expect("Couldn't write to file");
}
}
// Escape XML characters in attributes.
pub fn escape_attributes(attribute: &str) -> Cow<str> {
escape_string(attribute, match_attribute_html_char)
}
// Escape XML characters in data sections of tags. Note, this
// is different from escape_attributes() because double quotes
// and newline are not escaped by Excel.
pub fn escape_data(data: &str) -> Cow<str> {
escape_string(data, match_data_html_char)
}
// Escape XML characters in shared strings. In particular we need to escape
// control and non-printing characters in the range '\x00' - '\x1F'.
pub fn escape_si_data(data: &str) -> Cow<str> {
escape_string(data, match_shared_string_char)
}
// Match function for escape_attributes().
fn match_attribute_html_char(ch: char) -> Option<&'static str> {
match ch {
'&' => Some("&"),
'"' => Some("""),
'<' => Some("<"),
'>' => Some(">"),
'\n' => Some("
"),
_ => None,
}
}
// Match function for escape_data().
fn match_data_html_char(ch: char) -> Option<&'static str> {
match ch {
'&' => Some("&"),
'<' => Some("<"),
'>' => Some(">"),
_ => None,
}
}
// Match function for escape_si_data(). Excel escapes control characters and
// other non-printing characters in the range '\x00' - '\x1F' with _xHHHH_.
fn match_shared_string_char(ch: char) -> Option<&'static str> {
match ch {
'\x00' => Some("_x0000_"),
'\x01' => Some("_x0001_"),
'\x02' => Some("_x0002_"),
'\x03' => Some("_x0003_"),
'\x04' => Some("_x0004_"),
'\x05' => Some("_x0005_"),
'\x06' => Some("_x0006_"),
'\x07' => Some("_x0007_"),
'\x08' => Some("_x0008_"),
// No escape required for '\x09' = '\t'
// No escape required for '\x0A' = '\n'
'\x0B' => Some("_x000B_"),
'\x0C' => Some("_x000C_"),
'\x0D' => Some("_x000D_"),
'\x0E' => Some("_x000E_"),
'\x0F' => Some("_x000F_"),
'\x10' => Some("_x0010_"),
'\x11' => Some("_x0011_"),
'\x12' => Some("_x0012_"),
'\x13' => Some("_x0013_"),
'\x14' => Some("_x0014_"),
'\x15' => Some("_x0015_"),
'\x16' => Some("_x0016_"),
'\x17' => Some("_x0017_"),
'\x18' => Some("_x0018_"),
'\x19' => Some("_x0019_"),
'\x1A' => Some("_x001A_"),
'\x1B' => Some("_x001B_"),
'\x1C' => Some("_x001C_"),
'\x1D' => Some("_x001D_"),
'\x1E' => Some("_x001E_"),
'\x1F' => Some("_x001F_"),
'&' => Some("&"),
'<' => Some("<"),
'>' => Some(">"),
_ => None,
}
}
// Generic escape function with function pointer for the required handler.
fn escape_string<F>(original: &str, char_handler: F) -> Cow<str>
where
F: FnOnce(char) -> Option<&'static str> + Copy,
{
for (i, ch) in original.chars().enumerate() {
if char_handler(ch).is_some() {
let consumed_chars = original.chars().take(i);
let remaining_chars = original.chars().skip(i);
let mut escaped_string: String = consumed_chars.collect();
for ch in remaining_chars {
match char_handler(ch) {
Some(escaped_char) => escaped_string.push_str(escaped_char),
None => escaped_string.push(ch),
};
}
return Cow::Owned(escaped_string);
}
}
Cow::Borrowed(original)
}
// Excel escapes control characters with _xHHHH_ and also escapes any literal
// strings of that type by encoding the leading underscore. So "\0" -> _x0000_
// and "_x0000_" -> _x005F_x0000_.
fn escape_xml_escapes(si_string: &str) -> Cow<str> {
lazy_static! {
static ref XML_ESCAPE: Regex = Regex::new(r"(_x[0-9a-fA-F]{4}_)").unwrap();
}
XML_ESCAPE.replace_all(si_string, "_x005F$1")
}
// -----------------------------------------------------------------------
// Tests.
// -----------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::XMLWriter;
use pretty_assertions::assert_eq;
#[test]
fn test_xml_declaration() {
let expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
let mut writer = XMLWriter::default();
writer.xml_declaration();
let got = writer.read_to_string();
assert_eq!(got, expected);
}
#[test]
fn test_xml_start_tag_without_attributes() {
let expected = "<foo>";
let mut writer = XMLWriter::new();
writer.xml_start_tag("foo");
let got = writer.read_to_string();
assert_eq!(got, expected);
}
#[test]
fn test_xml_start_tag_without_attributes_implicit() {
let expected = "<foo>";
let attributes = vec![];
let mut writer = XMLWriter::new();
writer.xml_start_tag_attr("foo", &attributes);
let got = writer.read_to_string();
assert_eq!(got, expected);
}
#[test]
fn test_xml_start_tag_with_attributes() {
let expected = r#"<foo span="8" baz="7">"#;
let attributes = vec![("span", "8".to_string()), ("baz", "7".to_string())];
let mut writer = XMLWriter::new();
writer.xml_start_tag_attr("foo", &attributes);
let got = writer.read_to_string();
assert_eq!(got, expected);
}
#[test]
fn test_xml_end_tag() {
let expected = "</foo>";
let mut writer = XMLWriter::new();
writer.xml_end_tag("foo");
let got = writer.read_to_string();
assert_eq!(got, expected);
}
#[test]
fn test_xml_empty_tag() {
let expected = "<foo/>";
let mut writer = XMLWriter::new();
writer.xml_empty_tag("foo");
let got = writer.read_to_string();
assert_eq!(got, expected);
}
#[test]
fn test_xml_empty_tag_with_attributes() {
let expected = r#"<foo span="8"/>"#;
let attributes = vec![("span", "8".to_string())];
let mut writer = XMLWriter::new();
writer.xml_empty_tag_attr("foo", &attributes);
let got = writer.read_to_string();
assert_eq!(got, expected);
}
#[test]
fn test_xml_data_element() {
let expected = r#"<foo>bar</foo>"#;
let mut writer = XMLWriter::new();
writer.xml_data_element("foo", "bar");
let got = writer.read_to_string();
assert_eq!(got, expected);
}
#[test]
fn test_xml_data_element_with_attributes() {
let expected = r#"<foo span="8">bar</foo>"#;
let attributes = vec![("span", "8".to_string())];
let mut writer = XMLWriter::new();
writer.xml_data_element_attr("foo", "bar", &attributes);
let got = writer.read_to_string();
assert_eq!(got, expected);
}
#[test]
fn test_xml_data_element_with_escapes() {
let expected = r#"<foo span="8">&<>"</foo>"#;
let attributes = vec![("span", "8".to_string())];
let mut writer = XMLWriter::new();
writer.xml_data_element_attr("foo", "&<>\"", &attributes);
let got = writer.read_to_string();
assert_eq!(got, expected);
}
#[test]
fn test_xml_data_element_with_escapes_non_ascii() {
let expected = r#"<foo span="8" text="Ы&<>"
">Ы&<>"</foo>"#;
let attributes = vec![("span", "8".to_string()), ("text", "Ы&<>\"\n".to_owned())];
let mut writer = XMLWriter::new();
writer.xml_data_element_attr("foo", "Ы&<>\"", &attributes);
let got = writer.read_to_string();
assert_eq!(got, expected);
}
#[test]
fn test_xml_si_element() {
let expected = "<si><t>foo</t></si>";
let mut writer = XMLWriter::new();
writer.xml_si_element("foo", false);
let got = writer.read_to_string();
assert_eq!(got, expected);
}
#[test]
fn test_xml_si_element_whitespace() {
let expected = r#"<si><t xml:space="preserve"> foo</t></si>"#;
let mut writer = XMLWriter::new();
writer.xml_si_element(" foo", true);
let got = writer.read_to_string();
assert_eq!(got, expected);
}
}