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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
use std::cell::{Cell, RefCell};
use std::error::Error;
use std::fmt;
use std::rc::{Rc, Weak};
use std::usize;
use sax::{SaxDecoder, XmlToken};
use xmlerror::*;
#[derive(Clone)]
pub struct NodePtr {
rc_node: RcNode,
}
type RcNode = Rc<Node>;
fn wrap_rc_clone(rc_node: &RcNode) -> NodePtr {
return NodePtr{ rc_node: Rc::clone(rc_node) };
}
impl fmt::Debug for NodePtr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.node_type() {
NodeType::DocumentRoot => {
return write!(f, "(DocumentRoot)");
},
NodeType::Element => {
let mut str = String::new();
str += &"<";
str += &self.name();
for at in self.attributes().iter() {
str += &format!(r#" {}="{}""#, at.name(), at.value());
}
str += &">";
return write!(f, "{}", str);
},
NodeType::Text => {
return write!(f, "{}", self.value());
},
NodeType::Attribute => {
return write!(f, r#"{}="{}""#, self.name(), self.value());
},
_ => {
return write!(f, "");
},
}
}
}
impl fmt::Display for NodePtr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
return write!(f, "{:?}", self);
}
}
impl PartialEq for NodePtr {
fn eq(&self, other: &NodePtr) -> bool {
return Rc::ptr_eq(&self.rc_node, &other.rc_node)
}
}
impl Eq for NodePtr {
}
#[derive(Debug, PartialEq, Clone)]
pub enum NodeType {
DocumentRoot,
Element,
Text,
Comment,
XMLDecl,
Instruction,
Attribute,
Directive,
}
#[derive(Debug)]
struct Node {
node_type: NodeType,
order: Cell<i64>,
name: String,
value: String,
parent: Option<RefCell<Weak<Node>>>,
children: RefCell<Vec<RcNode>>,
attributes: RefCell<Vec<RcNode>>,
}
fn make_new_rc_node(node_type: NodeType,
parent: Option<&mut RcNode>,
name: &str, value: &str) -> RcNode {
let node = Rc::new(Node {
node_type,
order: Cell::new(0),
name: String::from(name),
value: String::from(value),
parent: match parent {
Some(p) => Some(RefCell::new(Rc::downgrade(p))),
None => None,
},
children: RefCell::new(vec!{}),
attributes: RefCell::new(vec!{}),
});
return node;
}
fn make_new_child_rc_node(node_type: NodeType, parent: &mut RcNode,
name: &str, value: &str, index_hint: usize) -> RcNode {
let node = make_new_rc_node(node_type, Some(parent), name, value);
if index_hint <= parent.children.borrow_mut().len() {
parent.children.borrow_mut().insert(index_hint, Rc::clone(&node));
} else {
parent.children.borrow_mut().push(Rc::clone(&node));
}
return node;
}
pub fn new_document(xml_string: &str) -> Result<NodePtr, Box<Error>> {
let mut dec = SaxDecoder::new(&String::from(xml_string))?;
let doc_root = make_new_rc_node(NodeType::DocumentRoot, None, "", "");
let mut curr_node = Rc::clone(&doc_root);
loop {
match dec.raw_token() {
Ok(XmlToken::EOF) => {
break;
},
Ok(XmlToken::StartElement{name, attr}) => {
let e = make_new_child_rc_node(NodeType::Element,
&mut curr_node,
name.as_str(), "", usize::MAX);
curr_node = Rc::clone(&e);
for at in attr.iter() {
let attr_node = make_new_rc_node(NodeType::Attribute,
Some(&mut curr_node), at.name(), at.value());
curr_node.attributes.borrow_mut().push(
Rc::clone(&attr_node));
}
},
Ok(XmlToken::EndElement{name}) => {
if curr_node.name.as_str() != name {
return Err(xml_syntax_error!(
"Element name mismatch: {} and {}",
curr_node.name.as_str(), name));
}
curr_node = match curr_node.parent {
Some(ref p) => p.borrow().upgrade().unwrap(),
None => Rc::clone(&curr_node),
};
},
Ok(XmlToken::CharData{chardata}) => {
make_new_child_rc_node(NodeType::Text,
&mut curr_node,
"", chardata.as_str(), usize::MAX);
},
Ok(XmlToken::ProcInst{target, inst}) => {
if target == "xml" {
make_new_child_rc_node(NodeType::XMLDecl,
&mut curr_node,
"xml", inst.as_str(), usize::MAX);
} else {
make_new_child_rc_node(NodeType::Instruction,
&mut curr_node,
target.as_str(), inst.as_str(), usize::MAX);
}
},
Ok(XmlToken::Comment{comment}) => {
make_new_child_rc_node(NodeType::Comment,
&mut curr_node,
"", comment.as_str(), usize::MAX);
},
Ok(XmlToken::Directive{directive: _directive}) => {},
Err(e) => {
return Err(xml_syntax_error!("XML syntax error: {}", e));
},
}
}
return Ok(NodePtr{rc_node: doc_root});
}
fn shallow_copy_rc_rels(target: &mut RcNode, source: &RcNode) {
for ch in source.children.borrow().iter() {
target.children.borrow_mut().push(Rc::clone(ch));
}
for at in source.attributes.borrow().iter() {
target.attributes.borrow_mut().push(Rc::clone(at));
}
}
impl NodePtr {
pub fn to_string(&self) -> String {
return to_string_with_indent(&self.unwrap_rc(), 0, 0);
}
pub fn to_pretty_string(&self) -> String {
return to_string_with_indent(&self.unwrap_rc(), 0, 4);
}
pub fn inner_xml(&self) -> String {
let mut s = String::new();
for ch in self.children().iter() {
s += &ch.to_string();
}
return s;
}
pub fn node_type(&self) -> NodeType {
return self.unwrap_rc().node_type.clone();
}
pub fn name(&self) -> String {
return self.unwrap_rc().name.clone();
}
pub fn value(&self) -> String {
return self.unwrap_rc().value.clone();
}
pub fn local_name(&self) -> String {
let name = &self.unwrap_rc().name;
let v: Vec<&str> = name.splitn(2, ":").collect();
if v.len() == 2 {
return String::from(v[1]);
} else {
return name.clone();
}
}
pub fn space_name(&self) -> String {
let name = &self.unwrap_rc().name;
let v: Vec<&str> = name.splitn(2, ":").collect();
if v.len() == 2 {
return String::from(v[0]);
} else {
return String::new();
}
}
pub fn namespace_uri(&self) -> String {
let mut xmlns_attr = String::from("xmlns");
let space = self.space_name();
if space.as_str() != "" {
xmlns_attr += &":";
xmlns_attr += &space;
}
let mut curr = self.unwrap_rc();
while (*curr).node_type != NodeType::DocumentRoot {
let val = wrap_rc_clone(&curr).attribute_value(xmlns_attr.as_str());
if let Some(value) = val {
return value.clone();
}
curr = match (*curr).parent {
Some(ref p) => p.borrow().upgrade().unwrap(),
None => return String::new(),
};
}
return String::new();
}
pub fn root(&self) -> NodePtr {
let mut curr = self.unwrap_rc();
loop {
curr = match (*curr).parent {
Some(ref p) => p.borrow().upgrade().unwrap(),
None => return wrap_rc_clone(&curr),
};
}
}
pub fn root_element(&self) -> NodePtr {
let doc_root = self.root();
for ch in doc_root.children().iter() {
if ch.node_type() == NodeType::Element {
return ch.clone();
}
}
return doc_root;
}
pub fn parent(&self) -> Option<NodePtr> {
match self.unwrap_rc().parent {
Some(ref p) => {
let parent_node = p.borrow().upgrade().unwrap();
return Some(wrap_rc_clone(&parent_node));
},
None => return None,
}
}
pub fn children(&self) -> Vec<NodePtr> {
let mut node_array: Vec<NodePtr> = vec!{};
let rc_node = self.unwrap_rc();
for ch in (*rc_node).children.borrow().iter() {
node_array.push(wrap_rc_clone(ch));
}
return node_array;
}
pub fn attributes(&self) -> Vec<NodePtr> {
let mut node_array: Vec<NodePtr> = vec!{};
let rc_node = self.unwrap_rc();
for at in (*rc_node).attributes.borrow().iter() {
node_array.push(wrap_rc_clone(at));
}
return node_array;
}
pub fn first_child(&self) -> Option<NodePtr> {
return self.nth_child(0);
}
pub fn nth_child(&self, n: usize) -> Option<NodePtr> {
let rc_node = self.unwrap_rc();
if n < rc_node.children.borrow().len() {
return Some(wrap_rc_clone(&(*rc_node).children.borrow()[n]));
} else {
return None
}
}
pub fn append_child(&self, new_child: &NodePtr) {
let rc_self = self.unwrap_rc();
let rc_new_child = new_child.unwrap_rc();
rc_self.children.borrow_mut().push(Rc::clone(&rc_new_child));
self.clear_document_order();
}
pub fn insert_as_previous_sibling(&self, new_node: &NodePtr) {
let parent = match self.parent() {
Some(p) => p,
None => return,
};
let n = parent.find_child_index(self);
if n != usize::MAX {
let mut rc_parent = parent.unwrap_rc();
let rc_new_node = new_node.unwrap_rc();
let mut rc_new_node_dup = make_new_child_rc_node(
rc_new_node.node_type.clone(),
&mut rc_parent,
&rc_new_node.name,
&rc_new_node.value,
n);
shallow_copy_rc_rels(&mut rc_new_node_dup, &rc_new_node);
}
self.clear_document_order();
}
pub fn insert_as_next_sibling(&self, new_node: &NodePtr) {
let parent = match self.parent() {
Some(p) => p,
None => return,
};
let n = parent.find_child_index(self);
if n != usize::MAX {
let mut rc_parent = parent.unwrap_rc();
let rc_new_node = new_node.unwrap_rc();
let mut rc_new_node_dup = make_new_child_rc_node(
rc_new_node.node_type.clone(),
&mut rc_parent,
&rc_new_node.name,
&rc_new_node.value,
n + 1);
shallow_copy_rc_rels(&mut rc_new_node_dup, &rc_new_node);
}
self.clear_document_order();
}
pub fn delete_child(&self, target: &NodePtr) {
let n = self.find_child_index(target);
if n != usize::MAX {
let rc_node = self.unwrap_rc();
(*rc_node).children.borrow_mut().remove(n);
}
self.clear_document_order();
}
pub fn replace_with(&self, new_node: &NodePtr) {
let parent = match self.parent() {
Some(p) => p,
None => return,
};
self.insert_as_previous_sibling(new_node);
parent.delete_child(self);
self.clear_document_order();
}
fn find_child_index(&self, target: &NodePtr) -> usize {
let rc_node = self.unwrap_rc();
let target_node = target.unwrap_rc();
for (i, ch) in (*rc_node).children.borrow().iter().enumerate() {
if Rc::ptr_eq(ch, &target_node) {
return i;
}
}
return usize::MAX;
}
pub fn attribute_value(&self, name: &str) -> Option<String> {
let r_index = self.find_attribute_index(name);
if r_index != usize::MAX {
let rc_node = self.unwrap_rc();
return Some((*rc_node).attributes.borrow()[r_index].value.clone());
} else {
return None;
}
}
pub fn set_attribute(&mut self, name: &str, value: &str) {
let mut rc_node = self.unwrap_rc();
let attr_node = make_new_rc_node(NodeType::Attribute,
Some(&mut rc_node), name, value);
let r_index = self.find_attribute_index(name);
if r_index != usize::MAX {
(*rc_node).attributes.borrow_mut().remove(r_index);
(*rc_node).attributes.borrow_mut().insert(r_index, Rc::clone(&attr_node));
} else {
(*rc_node).attributes.borrow_mut().push(Rc::clone(&attr_node));
}
self.clear_document_order();
}
pub fn delete_attribute(&mut self, name: &str) {
let r_index = self.find_attribute_index(name);
if r_index != usize::MAX {
let rc_node = self.unwrap_rc();
(*rc_node).attributes.borrow_mut().remove(r_index);
}
self.clear_document_order();
}
fn find_attribute_index(&self, name: &str) -> usize {
let rc_node = self.unwrap_rc();
for (i, at) in (*rc_node).attributes.borrow().iter().enumerate() {
if at.name == name {
return i;
}
}
return usize::MAX;
}
fn clear_document_order(&self) {
let root = self.root();
root.unwrap_rc().order.set(0);
}
pub fn document_order(&self) -> i64 {
let root = self.root();
if root.unwrap_rc().order.get() == 0 {
root.setup_document_order();
}
return self.unwrap_rc().order.get();
}
fn setup_document_order(&self) {
self.setup_document_order_sub(1);
}
fn setup_document_order_sub(&self, order_beg: i64) -> i64 {
let mut order = order_beg;
self.unwrap_rc().order.set(order);
order += 1;
for at in self.attributes().iter() {
at.unwrap_rc().order.set(order);
order += 1;
}
for ch in self.children().iter() {
order = ch.setup_document_order_sub(order + 1);
}
return order;
}
pub fn rc_clone(&self) -> NodePtr {
return NodePtr {
rc_node: Rc::clone(&self.rc_node),
};
}
fn unwrap_rc(&self) -> RcNode {
return Rc::clone(&self.rc_node);
}
}
fn to_string_with_indent(rc_node: &RcNode, indent: usize, step: usize) -> String {
match rc_node.node_type {
NodeType::DocumentRoot => {
let mut s = String::new();
for ch in rc_node.children.borrow().iter() {
s += &to_string_with_indent(ch, indent, step);
}
return s;
},
NodeType::Element => {
let mut s = String::new();
s += &format!("{}<{}", " ".repeat(indent), rc_node.name);
for at in rc_node.attributes.borrow().iter() {
s += &format!(r#" {}="{}""#,
at.name, encode_entity(&at.value));
}
if rc_node.children.borrow().len() == 0 {
s += &"/>";
} else {
s += &">";
s += &nl_if_positive(step);
for ch in rc_node.children.borrow().iter() {
s += &to_string_with_indent(ch, indent + step, step);
}
s += &format!("{}</{}>", " ".repeat(indent), rc_node.name);
}
s += &nl_if_positive(step);
return s;
},
NodeType::Text => {
return format!("{}{}{}",
&" ".repeat(indent),
&encode_entity(&(rc_node.value)),
&nl_if_positive(step));
},
NodeType::Comment => {
return format!("{}<!--{}-->{}",
&" ".repeat(indent),
&rc_node.value,
&nl_if_positive(step));
},
NodeType::XMLDecl => {
return format!("{}<?xml {}?>{}",
&" ".repeat(indent),
&rc_node.value,
&nl_if_positive(step));
},
NodeType::Instruction => {
return format!("{}<?{} {}?>{}",
&" ".repeat(indent),
&rc_node.name,
&rc_node.value,
&nl_if_positive(step));
},
_ => return String::new(),
}
}
fn encode_entity(s: &String) -> String {
let specs = [
[ "&", "&" ],
[ ">", ">" ],
[ "<", "<" ],
[ "\"", """ ],
[ "'", "'" ],
];
let mut str = s.clone();
for spec in specs.iter() {
str = str.replace(spec[0], spec[1]);
}
return str
}
fn nl_if_positive<'a>(n: usize) -> &'a str {
return if 0 < n { "\n" } else { "" };
}