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
use std::io;
use std::io::prelude::*;
use std::fmt;
use std::result;
use std::borrow::Cow;
use std::error::Error;
use common;
use name::{Name, OwnedName};
use attribute::Attribute;
use escape::{escape_str_attribute, escape_str_pcdata};
use common::XmlVersion;
use namespace::{NamespaceStack, NS_NO_PREFIX, NS_EMPTY_URI, NS_XMLNS_PREFIX, NS_XML_PREFIX};
use writer::config::EmitterConfig;
#[derive(Debug)]
pub enum EmitterError {
Io(io::Error),
DocumentStartAlreadyEmitted,
LastElementNameNotAvailable,
EndElementNameIsNotEqualToLastStartElementName,
EndElementNameIsNotSpecified
}
impl From<io::Error> for EmitterError {
fn from(err: io::Error) -> EmitterError {
EmitterError::Io(err)
}
}
impl fmt::Display for EmitterError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use std::error::Error;
try!(write!(f, "emitter error: "));
match *self {
EmitterError::Io(ref e) =>
write!(f, "I/O error: {}", e),
ref other =>
write!(f, "{}", other.description()),
}
}
}
impl Error for EmitterError {
fn description(&self) -> &str {
match *self {
EmitterError::Io(_) =>
"I/O error",
EmitterError::DocumentStartAlreadyEmitted =>
"document start event has already been emitted",
EmitterError::LastElementNameNotAvailable =>
"last element name is not available",
EmitterError::EndElementNameIsNotEqualToLastStartElementName =>
"end element name is not equal to last start element name",
EmitterError::EndElementNameIsNotSpecified =>
"end element name is not specified and can't be inferred",
}
}
}
pub type Result<T> = result::Result<T, EmitterError>;
pub struct Emitter {
config: EmitterConfig,
nst: NamespaceStack,
indent_level: usize,
indent_stack: Vec<IndentFlags>,
element_names: Vec<OwnedName>,
start_document_emitted: bool,
just_wrote_start_element: bool
}
impl Emitter {
pub fn new(config: EmitterConfig) -> Emitter {
Emitter {
config: config,
nst: NamespaceStack::empty(),
indent_level: 0,
indent_stack: vec!(IndentFlags::empty()),
element_names: Vec::new(),
start_document_emitted: false,
just_wrote_start_element: false
}
}
}
macro_rules! try_chain(
(ok_unit $e:expr) => ({try!($e); Ok(())});
(ignore $e:expr) => (try!($e));
($e:expr) => (Ok(try!($e)));
($e:expr, $($rest:tt)*) => ({
try!($e);
try_chain!($($rest)*)
})
);
macro_rules! wrapped_with(
($_self:ident; $before_name:ident ($arg:expr) and $after_name:ident, $body:expr) => ({
try!($_self.$before_name($arg));
let result = $body;
$_self.$after_name();
result
})
);
macro_rules! if_present(
($opt:ident, $body:expr) => ($opt.map(|$opt| $body).unwrap_or(Ok(())))
);
bitflags!(
struct IndentFlags: u8 {
const WROTE_NOTHING = 0;
const WROTE_MARKUP = 1;
const WROTE_TEXT = 2;
}
);
impl Emitter {
#[inline]
pub fn namespace_stack_mut(&mut self) -> &mut NamespaceStack {
&mut self.nst
}
#[inline]
fn wrote_text(&self) -> bool {
self.indent_stack.last().unwrap().contains(WROTE_TEXT)
}
#[inline]
fn wrote_markup(&self) -> bool {
self.indent_stack.last().unwrap().contains(WROTE_MARKUP)
}
#[inline]
fn set_wrote_text(&mut self) {
*self.indent_stack.last_mut().unwrap() = WROTE_TEXT;
}
#[inline]
fn set_wrote_markup(&mut self) {
*self.indent_stack.last_mut().unwrap() = WROTE_MARKUP;
}
#[inline]
fn reset_state(&mut self) {
*self.indent_stack.last_mut().unwrap() = WROTE_NOTHING;
}
fn write_newline<W: Write>(&mut self, target: &mut W, level: usize) -> Result<()> {
try!(target.write(self.config.line_separator.as_bytes()));
for _ in 0..level {
try!(target.write(self.config.indent_string.as_bytes()));
}
Ok(())
}
fn before_markup<W: Write>(&mut self, target: &mut W) -> Result<()> {
if self.config.perform_indent && !self.wrote_text() &&
(self.indent_level > 0 || self.wrote_markup()) {
let indent_level = self.indent_level;
try!(self.write_newline(target, indent_level));
if self.indent_level > 0 && self.config.indent_string.len() > 0 {
self.after_markup();
}
}
Ok(())
}
fn after_markup(&mut self) {
self.set_wrote_markup();
}
fn before_start_element<W: Write>(&mut self, target: &mut W) -> Result<()> {
try!(self.before_markup(target));
self.indent_stack.push(WROTE_NOTHING);
Ok(())
}
fn after_start_element(&mut self) {
self.after_markup();
self.indent_level += 1;
}
fn before_end_element<W: Write>(&mut self, target: &mut W) -> Result<()> {
if self.config.perform_indent && self.indent_level > 0 && self.wrote_markup() &&
!self.wrote_text() {
let indent_level = self.indent_level;
self.write_newline(target, indent_level - 1)
} else {
Ok(())
}
}
fn after_end_element(&mut self) {
if self.indent_level > 0 {
self.indent_level -= 1;
self.indent_stack.pop();
}
self.set_wrote_markup();
}
fn after_text(&mut self) {
self.set_wrote_text();
}
pub fn emit_start_document<W: Write>(&mut self, target: &mut W,
version: XmlVersion,
encoding: &str,
standalone: Option<bool>) -> Result<()> {
if self.start_document_emitted {
return Err(EmitterError::DocumentStartAlreadyEmitted);
}
self.start_document_emitted = true;
wrapped_with!(self; before_markup(target) and after_markup,
try_chain! {
write!(target, "<?xml version=\"{}\" encoding=\"{}\"", version, encoding),
if_present!(standalone,
write!(target, " standalone=\"{}\"",
if standalone { "yes" } else { "no" })),
write!(target, "?>")
}
)
}
fn check_document_started<W: Write>(&mut self, target: &mut W) -> Result<()> {
if !self.start_document_emitted && self.config.write_document_declaration {
self.emit_start_document(target, common::XmlVersion::Version10, "utf-8", None)
} else {
Ok(())
}
}
fn fix_non_empty_element<W: Write>(&mut self, target: &mut W) -> Result<()> {
if self.config.normalize_empty_elements && self.just_wrote_start_element {
self.just_wrote_start_element = false;
target.write(b">").map(|_| ()).map_err(From::from)
} else {
Ok(())
}
}
pub fn emit_processing_instruction<W: Write>(&mut self,
target: &mut W,
name: &str,
data: Option<&str>) -> Result<()> {
try!(self.check_document_started(target));
try!(self.fix_non_empty_element(target));
wrapped_with!(self; before_markup(target) and after_markup,
try_chain! {
write!(target, "<?{}", name),
if_present!(data, write!(target, " {}", data)),
write!(target, "?>")
}
)
}
fn emit_start_element_initial<W>(&mut self, target: &mut W,
name: Name,
attributes: &[Attribute]) -> Result<()>
where W: Write
{
try_chain! {
self.check_document_started(target),
self.fix_non_empty_element(target),
self.before_start_element(target),
write!(target, "<{}", name.repr_display()),
self.emit_current_namespace_attributes(target),
ignore self.emit_attributes(target, attributes)
}
self.after_start_element();
Ok(())
}
pub fn emit_start_element<W>(&mut self, target: &mut W,
name: Name,
attributes: &[Attribute]) -> Result<()>
where W: Write
{
if self.config.keep_element_names_stack {
self.element_names.push(name.to_owned());
}
try_chain! {
self.emit_start_element_initial(target, name, attributes),
{
self.just_wrote_start_element = true;
if self.config.normalize_empty_elements { Ok(()) }
else { write!(target, ">") }
}
}
}
pub fn emit_current_namespace_attributes<W>(&mut self, target: &mut W) -> Result<()>
where W: Write
{
for (prefix, uri) in self.nst.peek() {
try!(match prefix {
NS_XMLNS_PREFIX | NS_XML_PREFIX => Ok(()),
NS_NO_PREFIX => if uri != NS_EMPTY_URI {
write!(target, " xmlns=\"{}\"", uri)
} else { Ok(()) },
prefix => write!(target, " xmlns:{}=\"{}\"", prefix, uri)
});
}
Ok(())
}
pub fn emit_attributes<W: Write>(&mut self, target: &mut W,
attributes: &[Attribute]) -> Result<()> {
for attr in attributes.iter() {
try!(write!(
target, " {}=\"{}\"",
attr.name.repr_display(),
if self.config.perform_escaping { escape_str_attribute(attr.value) }
else { Cow::Borrowed(attr.value) }
))
}
Ok(())
}
pub fn emit_end_element<W: Write>(&mut self, target: &mut W,
name: Option<Name>) -> Result<()> {
let owned_name = if self.config.keep_element_names_stack {
Some(try!(self.element_names.pop().ok_or(EmitterError::LastElementNameNotAvailable)))
} else {
None
};
if let Some(ref last_name) = owned_name {
if let Some(ref name) = name {
if last_name.borrow() != *name {
return Err(EmitterError::EndElementNameIsNotEqualToLastStartElementName);
}
}
}
if let Some(name) = owned_name.as_ref().map(|n| n.borrow()).or(name) {
if self.config.normalize_empty_elements && self.just_wrote_start_element {
self.just_wrote_start_element = false;
let result = target.write(b" />").map_err(From::from);
self.after_end_element();
result.map(|_| ())
} else {
self.just_wrote_start_element = false;
wrapped_with!(self; before_end_element(target) and after_end_element,
write!(target, "</{}>", name.repr_display()).map_err(From::from)
)
}
} else {
Err(EmitterError::EndElementNameIsNotSpecified)
}
}
pub fn emit_cdata<W: Write>(&mut self, target: &mut W, content: &str) -> Result<()> {
try!(self.fix_non_empty_element(target));
if self.config.cdata_to_characters {
self.emit_characters(target, content)
} else {
try_chain! {
target.write(b"<![CDATA["),
target.write(content.as_bytes()),
ignore target.write(b"]]>")
};
self.after_text();
Ok(())
}
}
pub fn emit_characters<W: Write>(&mut self, target: &mut W,
content: &str) -> Result<()> {
try!(self.fix_non_empty_element(target));
try!(target.write(
(if self.config.perform_escaping { escape_str_pcdata(content) }
else { Cow::Borrowed(content) }).as_bytes()
));
self.after_text();
Ok(())
}
pub fn emit_comment<W: Write>(&mut self, target: &mut W, content: &str) -> Result<()> {
try!(self.fix_non_empty_element(target));
let autopad_comments = self.config.autopad_comments;
let write = |target: &mut W| -> Result<()> {
try_chain! {
target.write(b"<!--"),
if autopad_comments && !content.starts_with(char::is_whitespace) {
target.write(b" ")
} else { Ok(0) },
target.write(content.as_bytes()),
if autopad_comments && !content.ends_with(char::is_whitespace) {
target.write(b" ")
} else { Ok(0) },
ok_unit target.write(b"-->")
}
};
wrapped_with!(self; before_markup(target) and after_markup,
write(target)
)
}
}