svgdom 0.7.0

Library to represent an SVG as a DOM.
Documentation
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
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
commit 9e28e39df07736891a6d168b4c14f99d9346a475
Author: Reizner Evgeniy <razrfalcon@gmail.com>
Date:   Sun Jun 18 16:13:33 2017 +0300

    Nodes doesn't store the list of linked elements now.
    You should find linked elements manually from now.
    This simplifies attributes processing, because you can modify 'Attributes' struct directly now.

diff --git a/CHANGELOG.md b/CHANGELOG.md
index f25c804..a1e73a8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,9 +16,16 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
 - `Node::text` returns `Ref<String>` now.
 - Text will be preprocessed according to the
   [spec](https://www.w3.org/TR/SVG11/text.html#WhiteSpace) now.
+- Nodes doesn't store the list of linked elements now.
+  You should find linked elements manually from now.
+  This simplifies attributes processing, because you can modify `Attributes` struct directly now.
 
 ### Removed
 - `Error::UnresolvedAttribute`.
+- `Node::set_link_attribute`.
+- `Node::linked_nodes`.
+- `Node::is_used`.
+- `Node::uses_count`.
 
 ### Fixed
 - Additional whitespace during ArcTo writing.
diff --git a/Cargo.toml b/Cargo.toml
index 4b208c8..cad201c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -24,6 +24,7 @@ version = "0.4"
 
 [dev-dependencies]
 time = "0.1"
+unindent = "0.1"
 
 [features]
 default = ["parsing"]
diff --git a/src/attribute/attributes.rs b/src/attribute/attributes.rs
index 3d7c7cd..234f604 100644
--- a/src/attribute/attributes.rs
+++ b/src/attribute/attributes.rs
@@ -13,15 +13,13 @@ use {
     AttributeValue
 };
 
+// TODO: bench with HashTable
+// TODO: iter_svg() -> iter().svg() like in dom iterators
+
 pub type SvgAttrFilter<'a> = Filter<Iter<'a, Attribute>, fn(&&Attribute) -> bool>;
 pub type SvgAttrFilterMut<'a> = Filter<IterMut<'a, Attribute>, fn(&&mut Attribute) -> bool>;
 
 /// Wrapper around attributes list.
-///
-/// More low level API than in `Node`, but it supports getting a reference to the attribute,
-/// and not only copy like `Node`'s API.
-///
-/// Use with care, since it didn't perform many checks from `Node`'s API.
 pub struct Attributes(Vec<Attribute>);
 
 impl Attributes {
@@ -94,9 +92,6 @@ impl Attributes {
     }
 
     /// Inserts a new attribute. Previous will be overwritten.
-    ///
-    /// **Warning:** this method did not perform any checks for linked attributes.
-    /// If you want to insert an linked attribute - use `Node::set_link_attribute()`.
     pub fn insert(&mut self, attr: Attribute) {
         if self.0.capacity() == 0 {
             self.0.reserve(16);
@@ -104,15 +99,13 @@ impl Attributes {
 
         let idx = self.0.iter().position(|x| x.name == attr.name);
         match idx {
+            // We use braces to discard return value.
             Some(i) => { mem::replace(&mut self.0[i], attr); }
             None => self.0.push(attr),
         }
     }
 
     /// Creates a new attribute from name and value and inserts it. Previous will be overwritten.
-    ///
-    /// **Warning:** this method did not perform any checks for linked attributes.
-    /// If you want to insert an linked attribute - use `Node::set_link_attribute()`.
     pub fn insert_from<'a, N, T>(&mut self, name: N, value: T)
         where AttributeNameRef<'a>: From<N>, N: Copy, AttributeValue: From<T>
     {
@@ -120,9 +113,6 @@ impl Attributes {
     }
 
     /// Removes an existing attribute.
-    ///
-    /// **Warning:** this method did not perform any checks for linked attributes.
-    /// If you want to remove an linked attribute - use `Node::remove_attribute()`.
     pub fn remove<'a, N>(&mut self, name: N)
         where AttributeNameRef<'a>: From<N>
     {
diff --git a/src/dom/document.rs b/src/dom/document.rs
index 9a22144..444795a 100644
--- a/src/dom/document.rs
+++ b/src/dom/document.rs
@@ -185,7 +185,6 @@ impl Document {
             tag_name: tag_name.map(TagName::from),
             id: String::new(),
             attributes: Attributes::new(),
-            linked_nodes: Vec::new(),
             text: text,
         })))
     }
diff --git a/src/dom/iterators.rs b/src/dom/iterators.rs
index db3b9ef..9360ac4 100644
--- a/src/dom/iterators.rs
+++ b/src/dom/iterators.rs
@@ -2,11 +2,9 @@
 // License, v. 2.0. If a copy of the MPL was not distributed with this
 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
-use std::cell::Ref;
 use std::iter::Filter;
 
 use super::node::Node;
-use super::node_data::WeakLink;
 use super::node_type::NodeType;
 
 // TODO: maybe can be implemented as template or trait
@@ -188,37 +186,3 @@ impl Iterator for Parents {
 }
 
 filter_svg!(Parents);
-
-/// An iterator over linked nodes.
-pub struct LinkedNodes<'a> {
-    data: Ref<'a, Vec<WeakLink>>,
-    idx: usize,
-}
-
-impl<'a> LinkedNodes<'a> {
-    /// Constructs a new LinkedNodes iterator.
-    pub fn new(data: Ref<'a, Vec<WeakLink>>) -> LinkedNodes<'a> {
-        LinkedNodes {
-            data: data,
-            idx: 0,
-        }
-    }
-}
-
-impl<'a> Iterator for LinkedNodes<'a> {
-    type Item = Node;
-
-    fn next(&mut self) -> Option<Node> {
-        let i = self.idx;
-        self.idx += 1;
-
-        if i < self.data.len() {
-            match self.data[i].upgrade() {
-                Some(n) => Some(Node(n)),
-                None => None,
-            }
-        } else {
-            None
-        }
-    }
-}
diff --git a/src/dom/node.rs b/src/dom/node.rs
index 7753755..ac1adfa 100644
--- a/src/dom/node.rs
+++ b/src/dom/node.rs
@@ -10,7 +10,6 @@ use attribute::*;
 use {
     AttributeId,
     ElementId,
-    Error,
     Name,
     NameRef,
     SvgId,
@@ -50,10 +49,6 @@ impl SvgId for ElementId {
 ///  - List of SVG attributes.
 ///  - List of unknown attributes.
 ///  - Optional text data, which is used by non-element nodes.
-///
-/// Most of the API are designed to work with SVG elements and attributes.
-/// Processing of non-SVG data is pretty hard/verbose, since it's an SVG DOM, not an XML.
-// TODO: maybe copyable
 pub struct Node(pub Rc<RefCell<NodeData>>);
 
 impl Node {
@@ -65,6 +60,8 @@ impl Node {
     /// - Panics if the node is a root node.
     pub fn document(&self) -> Document {
         // TODO: will fail on root node
+        debug_assert!(self.node_type() != NodeType::Root);
+
         Document { root: Node(self.0.borrow().doc.as_ref().unwrap().upgrade().unwrap()) }
     }
 
@@ -137,6 +134,8 @@ impl Node {
         self.first_child().is_some()
     }
 
+    // TODO: add has_single_child
+
     /// Returns the first child of this node, unless it has no child.
     ///
     /// # Panics
@@ -196,54 +195,59 @@ impl Node {
 
     /// Removes this node and all it children from the tree.
     ///
-    /// Same as `detach()`, but also unlinks all linked nodes and attributes.
+    /// Same as `detach()`, but also removes all linked attributes from the tree.
+    ///
+    /// We have to iterate over all document attributes which can be very expensive.
     ///
     /// # Panics
     ///
     /// Panics if the node or one of its adjoining nodes or any children node is currently borrowed.
+    ///
+    /// # Examples
+    /// ```
+    /// use svgdom::{Document, ElementId, AttributeId};
+    ///
+    /// let doc = Document::from_str(
+    /// "<svg>
+    ///     <rect id='rect1'/>
+    ///     <use xlink:href='#rect1'/>
+    /// </svg>").unwrap();
+    ///
+    /// let rect_elem = doc.descendants().filter(|n| *n.id() == "rect1").next().unwrap();
+    /// let use_elem = doc.descendants().filter(|n| n.is_tag_name(ElementId::Use)).next().unwrap();
+    ///
+    /// assert_eq!(use_elem.has_attribute(AttributeId::XlinkHref), true);
+    ///
+    /// // The 'remove' method will remove 'rect' element and all it's children.
+    /// // Also it will remove all links to this element and it's children,
+    /// // so 'use' element will no longer have the 'xlink:href' attribute.
+    /// rect_elem.remove();
+    ///
+    /// assert_eq!(use_elem.has_attribute(AttributeId::XlinkHref), false);
+    /// ```
     pub fn remove(&self) {
-        Node::_remove(self);
-        self.detach();
-    }
+        let rm_nodes: Vec<Node> = self.descendants().svg().collect();
 
-    fn _remove(node: &Node) {
-        // remove link attributes, which will trigger nodes unlink
-        let mut ids: Vec<AttributeId> = node.attributes().iter_svg()
-                                        .filter(|&(_, a)| a.is_link() || a.is_func_link())
-                                        .map(|(id, _)| id)
-                                        .collect();
-        for id in &ids {
-            node.remove_attribute(*id);
-        }
-
-        // remove all attributes that linked to this node
-        for linked in node.linked_nodes().collect::<Vec<Node>>() {
-            ids.clear();
-
-            for (aid, attr) in linked.attributes().iter_svg() {
+        for n in self.document().descendants() {
+            let mut attrs = n.attributes_mut();
+            attrs.retain(|attr| {
                 match attr.value {
-                    AttributeValue::Link(ref link) | AttributeValue::FuncLink(ref link) => {
-                        if link == node {
-                            ids.push(aid);
-                        }
+                    AttributeValue::Link(ref link) |
+                    AttributeValue::FuncLink(ref link) => {
+                        !rm_nodes.contains(link)
                     }
-                    _ => {}
+                    _ => true,
                 }
-            }
-
-            for id in &ids {
-                linked.remove_attribute(*id);
-            }
+            });
         }
 
-        // repeat for children
-        for child in node.children().svg() {
-            Node::_remove(&child);
-        }
+        self.detach();
     }
 
     /// Removes only the children nodes specified by the predicate.
     ///
+    /// Uses `remove()`, not `detach()` internally.
+    ///
     /// Current node ignored.
     pub fn drain<P>(&self, f: P) -> usize
         where P: Fn(&Node) -> bool
@@ -528,6 +532,7 @@ impl Node {
         Ref::map(self.0.borrow(), |n| &n.id)
     }
 
+    // TODO: is used/needed?
     /// Returns `true` if node has a not empty ID.
     ///
     /// # Panics
@@ -637,25 +642,21 @@ impl Node {
     /// Use it to insert/create new attributes.
     /// For existing attributes use `Node::set_attribute_object()`.
     ///
-    /// You can't use this method to set referenced attributes.
-    /// Use `Node::set_link_attribute()` instead.
-    ///
     /// # Panics
     ///
     /// Panics if the node is currently borrowed.
     pub fn set_attribute<'a, N, T>(&self, name: N, value: T)
         where AttributeNameRef<'a>: From<N>, N: Copy, AttributeValue: From<T>
     {
-        debug_assert!(self.node_type() == NodeType::Element);
+        // TODO: allow Attribute
 
-        // we must remove existing attribute to prevent dangling links
-        self.remove_attribute(name);
+        debug_assert!(self.node_type() == NodeType::Element);
 
-        let a = Attribute::new(name, value);
         let mut attrs = self.attributes_mut();
-        attrs.insert(a);
+        attrs.insert_from(name, value);
     }
 
+    // TODO: remove
     /// Inserts a new SVG attribute into the attributes list.
     ///
     /// This method will overwrite an existing attribute with the same id.
@@ -665,128 +666,13 @@ impl Node {
     /// - Panics if the node is currently borrowed.
     /// - Panics if the attribute cause an ElementCrosslink error.
     pub fn set_attribute_object(&self, attr: Attribute) {
-        // TODO: fix stupid name
-
         debug_assert!(self.node_type() == NodeType::Element);
 
-        // we must remove existing attribute to prevent dangling links
-        self.remove_attribute(attr.name.into_ref());
-
-        if attr.is_svg() {
-            match attr.value {
-                AttributeValue::Link(ref iri) | AttributeValue::FuncLink(ref iri) => {
-                    let aid = attr.id().unwrap();
-                    self.set_link_attribute(aid, iri.clone()).unwrap();
-                    return;
-                }
-                _ => {}
-            }
-        }
-
         let mut attrs = self.attributes_mut();
         attrs.insert(attr);
     }
 
-    /// Inserts a new referenced SVG attribute into the attributes list.
-    ///
-    /// This method will overwrite an existing attribute with the same id.
-    ///
-    /// # Panics
-    ///
-    /// Panics if the node is currently borrowed.
-    ///
-    /// # Examples
-    /// ```
-    /// use svgdom::{Document, ValueId};
-    /// use svgdom::AttributeId as AId;
-    /// use svgdom::ElementId as EId;
-    ///
-    /// // Create a simple document.
-    /// let doc = Document::new();
-    /// let gradient = doc.create_element(EId::LinearGradient);
-    /// let rect = doc.create_element(EId::Rect);
-    ///
-    /// doc.append(&gradient);
-    /// doc.append(&rect);
-    ///
-    /// gradient.set_id("lg1");
-    /// rect.set_id("rect1");
-    ///
-    /// // Set a `fill` attribute value to the `none`.
-    /// // For now everything like in any other XML DOM library.
-    /// rect.set_attribute(AId::Fill, ValueId::None);
-    ///
-    /// // Now we want to fill our rect with a gradient.
-    /// // To do this we need to set a link attribute:
-    /// rect.set_link_attribute(AId::Fill, gradient.clone()).unwrap();
-    ///
-    /// // Now our fill attribute has a link to the `gradient` node.
-    /// // Not as text, aka `url(#lg1)`, but an actual reference.
-    ///
-    /// // This adds support for fast checking that the element is used. Which is very useful.
-    ///
-    /// // `gradient` is now used, since we link it.
-    /// assert_eq!(gradient.is_used(), true);
-    /// // Also, we can check how many elements are uses this `gradient`.
-    /// assert_eq!(gradient.uses_count(), 1);
-    /// // And even get this elements:
-    /// assert_eq!(gradient.linked_nodes().next().unwrap(), rect);
-    ///
-    /// // `rect` is unused, because no one has referenced attribute that has link to it.
-    /// assert_eq!(rect.is_used(), false);
-    ///
-    /// // Now, if we set other attribute value, `gradient` will be automatically unlinked.
-    /// rect.set_attribute(AId::Fill, ValueId::None);
-    /// // No one uses it anymore.
-    /// assert_eq!(gradient.is_used(), false);
-    /// ```
-    pub fn set_link_attribute(&self, id: AttributeId, node: Node) -> Result<(), Error> {
-        // TODO: rewrite to template specialization when it will be available
-        // TODO: check that node is element
-
-        debug_assert!(self.node_type() == NodeType::Element);
-
-        if node.id().is_empty() {
-            return Err(Error::ElementMustHaveAnId);
-        }
-
-        // check for recursion
-        if *self.id() == *node.id() {
-            return Err(Error::ElementCrosslink);
-        }
-
-        // check for recursion 2
-        {
-            let self_borrow = self.0.borrow();
-            let v = &self_borrow.linked_nodes;
-
-            if v.iter().any(|n| Node(n.upgrade().unwrap()) == node) {
-                return Err(Error::ElementCrosslink);
-            }
-        }
-
-        // we must remove existing attribute to prevent dangling links
-        self.remove_attribute(id);
-
-        {
-            let a = if id == AttributeId::XlinkHref {
-                Attribute::new(id, AttributeValue::Link(node.clone()))
-            } else {
-                Attribute::new(id, AttributeValue::FuncLink(node.clone()))
-            };
-
-            let mut attributes = self.attributes_mut();
-            attributes.insert(a);
-        }
-
-        {
-            let mut value_borrow = node.0.borrow_mut();
-            value_borrow.linked_nodes.push(Rc::downgrade(&self.0));
-        }
-
-        Ok(())
-    }
-
+    // TODO: remove
     /// Returns a copy of the attribute value by `id`.
     ///
     /// Use it only for simple `AttributeValue` types, and not for `String` and `Path`,
@@ -801,6 +687,7 @@ impl Node {
         self.attributes().get_value(id).cloned()
     }
 
+    // TODO: remove
     /// Returns a copy of the attribute by `id`.
     ///
     /// Use it only for attributes with simple `AttributeValue` types,
@@ -851,7 +738,11 @@ impl Node {
     ///
     /// Panics if the node is currently mutability borrowed.
     pub fn has_visible_attribute(&self, id: AttributeId) -> bool {
-        self.has_attribute(id) && self.attributes().get(id).unwrap().visible
+        if let Some(attr) = self.attributes().get(id) {
+            attr.visible
+        } else {
+            false
+        }
     }
 
     /// Returns `true` if the node has any of provided attributes.
@@ -895,29 +786,7 @@ impl Node {
     pub fn remove_attribute<'a, N>(&self, name: N)
         where AttributeNameRef<'a>: From<N>, N: Copy
     {
-        if !self.has_attribute(name) {
-            return;
-        }
-
-        let mut attrs = self.attributes_mut();
-
-        // we must unlink referenced attributes
-        if let Some(value) = attrs.get_value(name) {
-            match *value {
-                AttributeValue::Link(ref node) | AttributeValue::FuncLink(ref node) => {
-                    let mut self_borrow = node.0.borrow_mut();
-                    let ln = &mut self_borrow.linked_nodes;
-                    // this code can't panic, because we know that such node exist
-                    let index = ln.iter().position(|x| {
-                        same_rc(&x.upgrade().unwrap(), &self.0)
-                    }).unwrap();
-                    ln.remove(index);
-                }
-                _ => {}
-            }
-        }
-
-        attrs.remove(name);
+        self.attributes_mut().remove(name);
     }
 
     /// Removes attributes from the node.
@@ -931,39 +800,6 @@ impl Node {
             self.remove_attribute(*id);
         }
     }
-
-    /// Returns an iterator over linked nodes.
-    ///
-    /// # Panics
-    ///
-    /// Panics if the node is currently mutability borrowed.
-    pub fn linked_nodes(&self) -> LinkedNodes {
-        LinkedNodes::new(Ref::map(self.0.borrow(), |n| &n.linked_nodes))
-    }
-
-    /// Returns `true` if the current node is linked to any of the DOM nodes.
-    ///
-    /// See `Node::set_link_attribute()` for details.
-    ///
-    /// # Panics
-    ///
-    /// Panics if the node is currently mutability borrowed.
-    pub fn is_used(&self) -> bool {
-        let self_borrow = self.0.borrow();
-        !self_borrow.linked_nodes.is_empty()
-    }
-
-    /// Returns a number of nodes, which is linked to this node.
-    ///
-    /// See `Node::set_link_attribute()` for details.
-    ///
-    /// # Panics
-    ///
-    /// Panics if the node is currently mutability borrowed.
-    pub fn uses_count(&self) -> usize {
-        let self_borrow = self.0.borrow();
-        self_borrow.linked_nodes.len()
-    }
 }
 
 // TODO: move to Rc::ptr_eq (since 1.17) when we drop 1.13 version support
diff --git a/src/dom/node_data.rs b/src/dom/node_data.rs
index b329803..b26f803 100644
--- a/src/dom/node_data.rs
+++ b/src/dom/node_data.rs
@@ -25,7 +25,6 @@ pub struct NodeData {
     pub tag_name: Option<TagName>,
     pub id: String,
     pub attributes: Attributes,
-    pub linked_nodes: Vec<WeakLink>,
     pub text: String,
 }
 
@@ -33,6 +32,7 @@ impl NodeData {
     /// Detach a node from its parent and siblings. Children are not affected.
     pub fn detach(&mut self) {
         // TODO: trim names
+        // TODO: detach doc
 
         let parent_weak = self.parent.take();
         let previous_sibling_weak = self.previous_sibling.take();
diff --git a/src/error.rs b/src/error.rs
index 0ae2e2f..bb8a192 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -17,7 +17,7 @@ use simplecss::Error as CssParseError;
 pub enum Error {
     /// If you want to use referenced element inside link attribute,
     /// such element must have a non-empty ID.
-    ElementMustHaveAnId,
+    ElementMustHaveAnId, // TODO: currently unused
     /// A linked nodes can't reference each other.
     ///
     /// Example:
diff --git a/src/parser.rs b/src/parser.rs
index 6312db1..1b7c947 100644
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3,6 +3,7 @@
 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 // TODO: implement xml escape
+// TODO: split to submodules
 
 use std::str;
 use std::collections::HashMap;
@@ -163,8 +164,8 @@ pub fn parse_svg(text: &str, opt: &ParseOptions) -> Result<Document, Error> {
     }
 
     resolve_links(&post_data.links)?;
-
     prepare_text(&doc);
+    crosslink_check(&doc)?;
 
     Ok(doc)
 }
@@ -801,7 +802,13 @@ fn resolve_links(links: &Links) -> Result<(), Error> {
                         let s = d.iri.to_string();
                         return Err(Error::UnsupportedPaintFallback(s))
                     }
-                    None => d.node.set_link_attribute(d.attr_id, node.clone())?,
+                    None => {
+                        if d.attr_id == AttributeId::XlinkHref {
+                            d.node.set_attribute(d.attr_id, AttributeValue::Link(node.clone()))
+                        } else {
+                            d.node.set_attribute(d.attr_id, AttributeValue::FuncLink(node.clone()))
+                        }
+                    }
                 }
             }
             None => {
@@ -1167,3 +1174,46 @@ fn trim_text(text: &mut String, xmlspace: XmlSpace) {
         }
     }
 }
+
+// TODO: simplify
+fn crosslink_check(dom: &Document) -> Result<(), Error> {
+    // Check that element doesn't have links to itself.
+    for node in dom.descendants().svg() {
+        for attr in node.attributes().iter() {
+            match attr.value {
+                AttributeValue::Link(ref link) |
+                AttributeValue::FuncLink(ref link) => {
+                    if node == *link {
+                        return Err(Error::ElementCrosslink);
+                    }
+                }
+                _ => {}
+            }
+        }
+    }
+
+    // Check that two elements doesn't linked to each other.
+    for node1 in dom.descendants().svg() {
+        for attr1 in node1.attributes().iter() {
+            match attr1.value {
+                AttributeValue::Link(ref link1) |
+                AttributeValue::FuncLink(ref link1) => {
+                    for attr2 in link1.attributes().iter() {
+                        match attr2.value {
+                            AttributeValue::Link(ref link2) |
+                            AttributeValue::FuncLink(ref link2) => {
+                                if *link2 == node1 {
+                                    return Err(Error::ElementCrosslink);
+                                }
+                            }
+                            _ => {}
+                        }
+                    }
+                }
+                _ => {}
+            }
+        }
+    }
+
+    Ok(())
+}
diff --git a/src/postproc/gradients.rs b/src/postproc/gradients.rs
index 23d0176..dc20219 100644
--- a/src/postproc/gradients.rs
+++ b/src/postproc/gradients.rs
@@ -123,23 +123,35 @@ pub fn resolve_stop_attributes(doc: &Document) -> Result<(), Error> {
     Ok(())
 }
 
+// TODO: explain algorithm
 fn gen_order(doc: &Document, eid: ElementId) -> Vec<Node> {
-    let nodes = doc.descendants().svg().filter(|n| n.is_tag_name(eid))
-                   .collect::<Vec<Node>>();
+    let nodes: Vec<Node> = doc.descendants().svg().filter(|n| n.is_tag_name(eid)).collect();
+
+    let mut linked_nodes = Vec::with_capacity(nodes.len());
+    for node in &nodes {
+        let attrs = node.attributes();
+        if let Some(&AttributeValue::Link(ref link)) = attrs.get_value(AttributeId::XlinkHref) {
+            linked_nodes.push((node.clone(), link.clone()));
+        }
+    }
 
     let mut order = Vec::with_capacity(nodes.len());
 
     while order.len() != nodes.len() {
         for node in &nodes {
-            if order.iter().any(|on| on == node) {
+            if order.contains(node) {
                 continue;
             }
 
-            let c = node.linked_nodes().filter(|n| {
-                n.is_tag_name(eid) && !order.iter().any(|on| on == n)
-            }).count();
+            let mut is_any = false;
+
+            if let Some(v) = linked_nodes.iter().filter(|v| v.0 != *node).find(|v| *node == v.1) {
+                if !order.contains(&v.0) {
+                    is_any = true;
+                }
+            }
 
-            if c == 0 {
+            if !is_any {
                 order.push(node.clone());
             }
         }
diff --git a/src/postproc/mod.rs b/src/postproc/mod.rs
index 525825f..32a317f 100644
--- a/src/postproc/mod.rs
+++ b/src/postproc/mod.rs
@@ -17,6 +17,6 @@ pub use self::resolve_inherit::resolve_inherit;
 #[macro_use]
 mod macros;
 
+mod fix_attrs;
 mod gradients;
 mod resolve_inherit;
-mod fix_attrs;
diff --git a/tests/domapi.rs b/tests/domapi.rs
index 12cd4fb..fb5666e 100644
--- a/tests/domapi.rs
+++ b/tests/domapi.rs
@@ -4,138 +4,27 @@
 
 #[macro_use]
 extern crate svgdom;
-
-use svgdom::{Document, AttributeValue, Error, WriteToString, WriteOptions};
-use svgdom::AttributeId as AId;
-use svgdom::ElementId as EId;
-
-#[test]
-fn linked_attributes_1() {
-    let doc = Document::new();
-    let n1 = doc.create_element(EId::Svg);
-    let n2 = doc.create_element(EId::Svg);
-
-    doc.root().append(&n1);
-    doc.root().append(&n2);
-
-    n2.set_id("2");
-
-    n1.set_link_attribute(AId::XlinkHref, n2.clone()).unwrap();
-
-    assert_eq!(n1.is_used(), false);
-    assert_eq!(n2.is_used(), true);
-
-    assert_eq!(n2.linked_nodes().next().unwrap(), n1);
-}
-
-#[test]
-fn linked_attributes_2() {
-    let doc = Document::new();
-    let n1 = doc.create_element(EId::Svg);
-    let n2 = doc.create_element(EId::Svg);
-
-    n1.set_id("1");
-    n2.set_id("2");
-
-    doc.root().append(&n1);
-    doc.root().append(&n2);
-
-    n1.set_link_attribute(AId::XlinkHref, n2.clone()).unwrap();
-
-    // recursion error
-    assert_eq!(n2.set_link_attribute(AId::XlinkHref, n1.clone()).unwrap_err(),
-               Error::ElementCrosslink);
-}
-
-#[test]
-fn linked_attributes_3() {
-    let doc = Document::new();
-
-    {
-        let n1 = doc.create_element(EId::Svg);
-        let n2 = doc.create_element(EId::Svg);
-
-        doc.root().append(&n1);
-        doc.root().append(&n2);
-
-        n1.set_id("1");
-        n2.set_id("2");
-
-        n1.set_link_attribute(AId::XlinkHref, n2.clone()).unwrap();
-
-        assert_eq!(n1.is_used(), false);
-        assert_eq!(n2.is_used(), true);
-    }
-
-    {
-        // remove n1
-        let n = doc.descendants().next().unwrap();
-        n.remove();
-    }
-
-    {
-        // n2 should became unused
-        let n = doc.descendants().next().unwrap();
-        assert_eq!(n.is_used(), false);
-    }
-}
-
-#[test]
-fn linked_attributes_4() {
-    let doc = Document::new();
-
-    {
-        let n1 = doc.create_element(EId::Svg);
-        let n2 = doc.create_element(EId::Svg);
-
-        doc.root().append(&n1);
-        doc.root().append(&n2);
-
-        n1.set_id("1");
-        n2.set_id("2");
-
-        n1.set_link_attribute(AId::XlinkHref, n2.clone()).unwrap();
-
-        assert_eq!(n1.is_used(), false);
-        assert_eq!(n2.is_used(), true);
-    }
-
-    {
-        // remove n2
-        let n = doc.descendants().nth(1).unwrap();
-        n.remove();
-    }
-
-    {
-        // xlink:href attribute from n1 should be removed
-        let n = doc.descendants().next().unwrap();
-        assert_eq!(n.has_attribute(AId::XlinkHref), false);
-    }
-}
-
-#[test]
-fn linked_attributes_5() {
-    let doc = Document::new();
-    let n1 = doc.create_element(EId::Svg);
-    let n2 = doc.create_element(EId::Svg);
-
-    doc.root().append(&n1);
-    doc.root().append(&n2);
-
-    n1.set_id("1");
-    n2.set_id("2");
-
-    // no matter how many times we insert/clone/link same node,
-    // amount of linked nodes in n1 must be 1
-    n2.set_link_attribute(AId::Fill, n1.clone()).unwrap();
-    n2.set_link_attribute(AId::Fill, n1.clone()).unwrap();
-    n2.set_link_attribute(AId::Fill, n1.clone()).unwrap();
-    n2.set_link_attribute(AId::Fill, n1.clone()).unwrap();
-
-    assert_eq!(n1.is_used(), true);
-    assert_eq!(n2.is_used(), false);
-
-    assert_eq!(n1.uses_count(), 1);
+extern crate unindent;
+
+use unindent::unindent;
+
+use svgdom::{
+    AttributeId as AId,
+    AttributeValue,
+    Document,
+    ElementId as EId,
+    WriteOptions,
+    WriteToString,
+};
+
+macro_rules! write_opt_for_tests {
+    () => ({
+        use WriteOptions;
+        let mut opt = WriteOptions::default();
+        opt.use_single_quote = true;
+        opt.simplify_transform_matrices = true;
+        opt
+    })
 }
 
 #[test]
@@ -416,3 +305,97 @@ fn deep_copy_3() {
 </svg>
 ");
 }
+
+#[test]
+fn node_remove_1() {
+    let in_text =
+        "<svg>
+            <rect id='r1'/>
+            <use xlink:href='#r1'/>
+        </svg>";
+
+    let doc = Document::from_str(in_text).unwrap();
+
+    let rect = doc.descendants().find(|n| *n.id() == "r1").unwrap();
+    rect.remove();
+
+    let out_text = unindent(
+        "<svg>
+            <use/>
+        </svg>
+    ");
+
+    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), out_text);
+}
+
+#[test]
+fn node_remove_2() {
+    let in_text =
+        "<svg>
+            <linearGradient id='lg1'/>
+            <rect id='r1' fill='url(#lg1)'/>
+        </svg>";
+
+    let doc = Document::from_str(in_text).unwrap();
+
+    let lg = doc.descendants().find(|n| *n.id() == "lg1").unwrap();
+    lg.remove();
+
+    let out_text = unindent(
+        "<svg>
+            <rect id='r1'/>
+        </svg>
+    ");
+
+    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), out_text);
+}
+
+#[test]
+fn node_remove_3() {
+    let in_text =
+        "<svg>
+            <rect id='r1' fill='url(#lg1)'/>
+            <linearGradient id='lg1'/>
+            <rect id='r2' fill='url(#lg1)'/>
+            <rect id='r3' fill='url(#lg1)'/>
+        </svg>";
+
+    let doc = Document::from_str(in_text).unwrap();
+
+    let lg = doc.descendants().find(|n| *n.id() == "lg1").unwrap();
+    lg.remove();
+
+    let out_text = unindent(
+        "<svg>
+            <rect id='r1'/>
+            <rect id='r2'/>
+            <rect id='r3'/>
+        </svg>
+    ");
+
+    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), out_text);
+}
+
+#[test]
+fn node_remove_4() {
+    let in_text =
+        "<svg>
+            <defs id='defs1'>
+                <linearGradient id='lg1'/>
+            </defs>
+            <rect id='r1' fill='url(#lg1)'/>
+        </svg>";
+
+    let doc = Document::from_str(in_text).unwrap();
+
+    let defs = doc.descendants().find(|n| *n.id() == "defs1").unwrap();
+    defs.remove();
+
+    let out_text = unindent(
+        "<svg>
+            <rect id='r1'/>
+        </svg>
+    ");
+
+    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), out_text);
+}
diff --git a/tests/generator.rs b/tests/generator.rs
index ccaa8c4..ee29314 100644
--- a/tests/generator.rs
+++ b/tests/generator.rs
@@ -5,7 +5,7 @@
 #[macro_use]
 extern crate svgdom;
 
-use svgdom::{Document, WriteOptions, WriteToString, NodeType, Indent};
+use svgdom::{Document, WriteOptions, WriteToString, NodeType, Indent, AttributeValue};
 use svgdom::AttributeId as AId;
 use svgdom::ElementId as EId;
 use svgdom::types::{Transform, Length, LengthUnit, Color};
@@ -96,7 +96,7 @@ fn links_1() {
     doc.append(&svg_n);
     svg_n.append(&use_n);
 
-    use_n.set_link_attribute(AId::XlinkHref, svg_n).unwrap();
+    use_n.set_attribute(AId::XlinkHref, AttributeValue::Link(svg_n));
 
     assert_eq_text!(doc.to_string(),
 "<svg id=\"svg1\">
@@ -118,7 +118,7 @@ fn links_2() {
     svg_n.append(&lg_n);
     svg_n.append(&rect_n);
 
-    rect_n.set_link_attribute(AId::Fill, lg_n).unwrap();
+    rect_n.set_attribute(AId::Fill, AttributeValue::FuncLink(lg_n));
 
     assert_eq_text!(doc.to_string(),
 "<svg>
diff --git a/tests/parser.rs b/tests/parser.rs
index 9275081..ca2e3b8 100644
--- a/tests/parser.rs
+++ b/tests/parser.rs
@@ -7,29 +7,27 @@ extern crate svgdom;
 extern crate simplecss;
 
 use svgdom::{
+    AttributeId as AId,
+    AttributeValue,
     Document,
-    ParseOptions,
+    ElementId as EId,
     Error,
     ErrorPos,
     Name,
     NodeType,
+    ParseOptions,
     ValueId,
-    WriteToString
+    WriteOptions,
+    WriteToString,
 };
 use svgdom::types::Color;
-use svgdom::AttributeValue;
-use svgdom::AttributeId as AId;
-use svgdom::ElementId as EId;
 
 use simplecss::Error as CssParseError;
 
-macro_rules! write_opt_for_tests {
-    () => ({
-        use svgdom::WriteOptions;
-        let mut opt = WriteOptions::default();
-        opt.use_single_quote = true;
-        opt
-    })
+fn write_options() -> WriteOptions {
+    let mut opt = WriteOptions::default();
+    opt.use_single_quote = true;
+    opt
 }
 
 macro_rules! test_resave {
@@ -37,7 +35,7 @@ macro_rules! test_resave {
         #[test]
         fn $name() {
             let doc = Document::from_str($in_text).unwrap();
-            assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), $out_text);
+            assert_eq_text!(doc.to_string_with_opt(&write_options()), $out_text);
         }
     )
 }
@@ -537,7 +535,6 @@ fn parse_iri_1() {
     let rg = child.children().nth(0).unwrap();
     let rect = child.children().nth(1).unwrap();
 
-    assert_eq!(rg.is_used(), true);
     assert_eq!(rect.attribute_value(AId::Fill).unwrap(), AttributeValue::FuncLink(rg));
 }
 
@@ -555,7 +552,6 @@ fn parse_iri_2() {
     let rect = child.children().nth(0).unwrap();
     let rg = child.children().nth(1).unwrap();
 
-    assert_eq!(rg.is_used(), true);
     assert_eq!(rect.attribute_value(AId::Fill).unwrap(), AttributeValue::FuncLink(rg));
 }
 
@@ -754,7 +750,7 @@ fn skip_comments_1() {
 "<!--comment-->
 <svg/>", &opt).unwrap();
 
-    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+    assert_eq_text!(doc.to_string_with_opt(&write_options()),
 "<svg/>
 ");
 }
@@ -767,7 +763,7 @@ fn skip_declaration_1() {
 "<?xml version='1.0'?>
 <svg/>", &opt).unwrap();
 
-    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+    assert_eq_text!(doc.to_string_with_opt(&write_options()),
 "<svg/>
 ");
 }
@@ -782,7 +778,7 @@ fn skip_unknown_elements_1() {
     <rect/>
 </svg>", &opt).unwrap();
 
-    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+    assert_eq_text!(doc.to_string_with_opt(&write_options()),
 "<svg>
     <rect/>
 </svg>
@@ -803,7 +799,7 @@ fn skip_unknown_elements_2() {
     <rect/>
 </svg>", &opt).unwrap();
 
-    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+    assert_eq_text!(doc.to_string_with_opt(&write_options()),
 "<svg>
     <rect/>
 </svg>
@@ -824,7 +820,7 @@ fn skip_unknown_elements_3() {
     <rect/>
 </svg>", &opt).unwrap();
 
-    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+    assert_eq_text!(doc.to_string_with_opt(&write_options()),
 "<svg>
     <rect/>
 </svg>
@@ -842,7 +838,7 @@ fn skip_unknown_elements_4() {
     <rect/>
 </svg>", &opt).unwrap();
 
-    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+    assert_eq_text!(doc.to_string_with_opt(&write_options()),
 "<svg>
     <rect/>
 </svg>
@@ -857,7 +853,7 @@ fn skip_unknown_attributes_1() {
 "<svg fill='#ff0000' test='1' qwe='zzz' xmlns='http://www.w3.org/2000/svg' \
 xmlns:xlink='http://www.w3.org/1999/xlink'/>", &opt).unwrap();
 
-    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+    assert_eq_text!(doc.to_string_with_opt(&write_options()),
 "<svg fill='#ff0000' xmlns='http://www.w3.org/2000/svg' \
 xmlns:xlink='http://www.w3.org/1999/xlink'/>
 ");
@@ -868,7 +864,7 @@ fn parse_px_unit_on_1() {
     let mut opt = ParseOptions::default();
     opt.parse_px_unit = true;
     let doc = Document::from_str_with_opt("<svg x='10px'/>", &opt).unwrap();
-    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), "<svg x='10px'/>\n");
+    assert_eq_text!(doc.to_string_with_opt(&write_options()), "<svg x='10px'/>\n");
 }
 
 #[test]
@@ -876,7 +872,7 @@ fn parse_px_unit_off_1() {
     let mut opt = ParseOptions::default();
     opt.parse_px_unit = false;
     let doc = Document::from_str_with_opt("<svg x='10px'/>", &opt).unwrap();
-    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()), "<svg x='10'/>\n");
+    assert_eq_text!(doc.to_string_with_opt(&write_options()), "<svg x='10'/>\n");
 }
 
 #[test]
@@ -884,7 +880,7 @@ fn parse_px_unit_off_2() {
     let mut opt = ParseOptions::default();
     opt.parse_px_unit = false;
     let doc = Document::from_str_with_opt("<svg stroke-dasharray='10px 20px'/>", &opt).unwrap();
-    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+    assert_eq_text!(doc.to_string_with_opt(&write_options()),
                     "<svg stroke-dasharray='10 20'/>\n");
 }
 
@@ -902,7 +898,7 @@ fn skip_unresolved_classes_1() {
     <g class='fil1 fil4 str1 fil5'/>
 </svg>", &opt).unwrap();
 
-    assert_eq_text!(doc.to_string_with_opt(&write_opt_for_tests!()),
+    assert_eq_text!(doc.to_string_with_opt(&write_options()),
 "<svg>
     <g class='fil3' fill='#0000ff'/>
     <g class='fil4 fil5' fill='#0000ff' stroke='#0000ff'/>
@@ -910,5 +906,28 @@ fn skip_unresolved_classes_1() {
 ");
 }
 
+#[test]
+fn crosslink_1() {
+    let doc = Document::from_str(
+        "<svg>
+            <linearGradient id='lg1' xlink:href='#lg1'/>
+        </svg>
+        "
+    );
+    assert_eq!(doc.err().unwrap(), Error::ElementCrosslink);
+}
+
+#[test]
+fn crosslink_2() {
+    let doc = Document::from_str(
+        "<svg>
+            <linearGradient id='lg1' xlink:href='#lg2'/>
+            <linearGradient id='lg2' xlink:href='#lg1'/>
+        </svg>
+        "
+    );
+    assert_eq!(doc.err().unwrap(), Error::ElementCrosslink);
+}
+
 // TODO: this
 // p { font-family: "Font 1", "Font 2", Georgia, Times, serif; }