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
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeConstants;
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use crate::dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods;
use crate::dom::bindings::codegen::Bindings::RangeBinding::RangeConstants;
use crate::dom::bindings::codegen::Bindings::RangeBinding::RangeMethods;
use crate::dom::bindings::codegen::Bindings::TextBinding::TextMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::inheritance::{CharacterDataTypeId, NodeTypeId};
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot, MutDom};
use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::trace::JSTraceable;
use crate::dom::bindings::weakref::{WeakRef, WeakRefVec};
use crate::dom::characterdata::CharacterData;
use crate::dom::document::Document;
use crate::dom::documentfragment::DocumentFragment;
use crate::dom::element::Element;
use crate::dom::htmlscriptelement::HTMLScriptElement;
use crate::dom::node::{Node, ShadowIncluding, UnbindContext};
use crate::dom::selection::Selection;
use crate::dom::text::Text;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use js::jsapi::JSTracer;
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use std::cell::{Cell, UnsafeCell};
use std::cmp::{Ord, Ordering, PartialEq, PartialOrd};

#[dom_struct]
pub struct Range {
    reflector_: Reflector,
    start: BoundaryPoint,
    end: BoundaryPoint,
    // A range that belongs to a Selection needs to know about it
    // so selectionchange can fire when the range changes.
    // A range shouldn't belong to more than one Selection at a time,
    // but from the spec as of Feb 1 2020 I can't rule out a corner case like:
    // * Select a range R in document A, from node X to Y
    // * Insert everything from X to Y into document B
    // * Set B's selection's range to R
    // which leaves R technically, and observably, associated with A even though
    // it will fail the same-root-node check on many of A's selection's methods.
    associated_selections: DomRefCell<Vec<Dom<Selection>>>,
}

impl Range {
    fn new_inherited(
        start_container: &Node,
        start_offset: u32,
        end_container: &Node,
        end_offset: u32,
    ) -> Range {
        Range {
            reflector_: Reflector::new(),
            start: BoundaryPoint::new(start_container, start_offset),
            end: BoundaryPoint::new(end_container, end_offset),
            associated_selections: DomRefCell::new(vec![]),
        }
    }

    pub fn new_with_doc(document: &Document) -> DomRoot<Range> {
        let root = document.upcast();
        Range::new(document, root, 0, root, 0)
    }

    pub fn new(
        document: &Document,
        start_container: &Node,
        start_offset: u32,
        end_container: &Node,
        end_offset: u32,
    ) -> DomRoot<Range> {
        let range = reflect_dom_object(
            Box::new(Range::new_inherited(
                start_container,
                start_offset,
                end_container,
                end_offset,
            )),
            document.window(),
        );
        start_container.ranges().push(WeakRef::new(&range));
        if start_container != end_container {
            end_container.ranges().push(WeakRef::new(&range));
        }
        range
    }

    // https://dom.spec.whatwg.org/#dom-range
    #[allow(non_snake_case)]
    pub fn Constructor(window: &Window) -> Fallible<DomRoot<Range>> {
        let document = window.Document();
        Ok(Range::new_with_doc(&document))
    }

    // https://dom.spec.whatwg.org/#contained
    fn contains(&self, node: &Node) -> bool {
        match (
            bp_position(node, 0, &self.StartContainer(), self.StartOffset()),
            bp_position(node, node.len(), &self.EndContainer(), self.EndOffset()),
        ) {
            (Some(Ordering::Greater), Some(Ordering::Less)) => true,
            _ => false,
        }
    }

    // https://dom.spec.whatwg.org/#partially-contained
    fn partially_contains(&self, node: &Node) -> bool {
        self.StartContainer()
            .inclusive_ancestors(ShadowIncluding::No)
            .any(|n| &*n == node) !=
            self.EndContainer()
                .inclusive_ancestors(ShadowIncluding::No)
                .any(|n| &*n == node)
    }

    // https://dom.spec.whatwg.org/#concept-range-clone
    fn contained_children(
        &self,
    ) -> Fallible<(
        Option<DomRoot<Node>>,
        Option<DomRoot<Node>>,
        Vec<DomRoot<Node>>,
    )> {
        let start_node = self.StartContainer();
        let end_node = self.EndContainer();
        // Steps 5-6.
        let common_ancestor = self.CommonAncestorContainer();

        let first_contained_child = if start_node.is_inclusive_ancestor_of(&end_node) {
            // Step 7.
            None
        } else {
            // Step 8.
            common_ancestor
                .children()
                .find(|node| Range::partially_contains(self, node))
        };

        let last_contained_child = if end_node.is_inclusive_ancestor_of(&start_node) {
            // Step 9.
            None
        } else {
            // Step 10.
            common_ancestor
                .rev_children()
                .find(|node| Range::partially_contains(self, node))
        };

        // Step 11.
        let contained_children: Vec<DomRoot<Node>> = common_ancestor
            .children()
            .filter(|n| self.contains(n))
            .collect();

        // Step 12.
        if contained_children.iter().any(|n| n.is_doctype()) {
            return Err(Error::HierarchyRequest);
        }

        Ok((
            first_contained_child,
            last_contained_child,
            contained_children,
        ))
    }

    // https://dom.spec.whatwg.org/#concept-range-bp-set
    fn set_start(&self, node: &Node, offset: u32) {
        if &self.start.node != node || self.start.offset.get() != offset {
            self.report_change();
        }
        if &self.start.node != node {
            if self.start.node == self.end.node {
                node.ranges().push(WeakRef::new(&self));
            } else if &self.end.node == node {
                self.StartContainer().ranges().remove(self);
            } else {
                node.ranges()
                    .push(self.StartContainer().ranges().remove(self));
            }
        }
        self.start.set(node, offset);
    }

    // https://dom.spec.whatwg.org/#concept-range-bp-set
    fn set_end(&self, node: &Node, offset: u32) {
        if &self.end.node != node || self.end.offset.get() != offset {
            self.report_change();
        }
        if &self.end.node != node {
            if self.end.node == self.start.node {
                node.ranges().push(WeakRef::new(&self));
            } else if &self.start.node == node {
                self.EndContainer().ranges().remove(self);
            } else {
                node.ranges()
                    .push(self.EndContainer().ranges().remove(self));
            }
        }
        self.end.set(node, offset);
    }

    // https://dom.spec.whatwg.org/#dom-range-comparepointnode-offset
    fn compare_point(&self, node: &Node, offset: u32) -> Fallible<Ordering> {
        let start_node = self.StartContainer();
        let start_node_root = start_node
            .inclusive_ancestors(ShadowIncluding::No)
            .last()
            .unwrap();
        let node_root = node
            .inclusive_ancestors(ShadowIncluding::No)
            .last()
            .unwrap();
        if start_node_root != node_root {
            // Step 1.
            return Err(Error::WrongDocument);
        }
        if node.is_doctype() {
            // Step 2.
            return Err(Error::InvalidNodeType);
        }
        if offset > node.len() {
            // Step 3.
            return Err(Error::IndexSize);
        }
        if let Ordering::Less = bp_position(node, offset, &start_node, self.StartOffset()).unwrap()
        {
            // Step 4.
            return Ok(Ordering::Less);
        }
        if let Ordering::Greater =
            bp_position(node, offset, &self.EndContainer(), self.EndOffset()).unwrap()
        {
            // Step 5.
            return Ok(Ordering::Greater);
        }
        // Step 6.
        Ok(Ordering::Equal)
    }

    pub fn associate_selection(&self, selection: &Selection) {
        let mut selections = self.associated_selections.borrow_mut();
        if !selections.iter().any(|s| &**s == selection) {
            selections.push(Dom::from_ref(selection));
        }
    }

    pub fn disassociate_selection(&self, selection: &Selection) {
        self.associated_selections
            .borrow_mut()
            .retain(|s| &**s != selection);
    }

    fn report_change(&self) {
        self.associated_selections
            .borrow()
            .iter()
            .for_each(|s| s.queue_selectionchange_task());
    }
}

impl RangeMethods for Range {
    // https://dom.spec.whatwg.org/#dom-range-startcontainer
    fn StartContainer(&self) -> DomRoot<Node> {
        self.start.node.get()
    }

    // https://dom.spec.whatwg.org/#dom-range-startoffset
    fn StartOffset(&self) -> u32 {
        self.start.offset.get()
    }

    // https://dom.spec.whatwg.org/#dom-range-endcontainer
    fn EndContainer(&self) -> DomRoot<Node> {
        self.end.node.get()
    }

    // https://dom.spec.whatwg.org/#dom-range-endoffset
    fn EndOffset(&self) -> u32 {
        self.end.offset.get()
    }

    // https://dom.spec.whatwg.org/#dom-range-collapsed
    fn Collapsed(&self) -> bool {
        self.start == self.end
    }

    // https://dom.spec.whatwg.org/#dom-range-commonancestorcontainer
    fn CommonAncestorContainer(&self) -> DomRoot<Node> {
        self.EndContainer()
            .common_ancestor(&self.StartContainer(), ShadowIncluding::No)
            .expect("Couldn't find common ancestor container")
    }

    // https://dom.spec.whatwg.org/#dom-range-setstart
    fn SetStart(&self, node: &Node, offset: u32) -> ErrorResult {
        if node.is_doctype() {
            // Step 1.
            Err(Error::InvalidNodeType)
        } else if offset > node.len() {
            // Step 2.
            Err(Error::IndexSize)
        } else {
            // Step 3.
            self.set_start(node, offset);
            if !(self.start <= self.end) {
                // Step 4.
                self.set_end(node, offset);
            }
            Ok(())
        }
    }

    // https://dom.spec.whatwg.org/#dom-range-setend
    fn SetEnd(&self, node: &Node, offset: u32) -> ErrorResult {
        if node.is_doctype() {
            // Step 1.
            Err(Error::InvalidNodeType)
        } else if offset > node.len() {
            // Step 2.
            Err(Error::IndexSize)
        } else {
            // Step 3.
            self.set_end(node, offset);
            if !(self.end >= self.start) {
                // Step 4.
                self.set_start(node, offset);
            }
            Ok(())
        }
    }

    // https://dom.spec.whatwg.org/#dom-range-setstartbefore
    fn SetStartBefore(&self, node: &Node) -> ErrorResult {
        let parent = node.GetParentNode().ok_or(Error::InvalidNodeType)?;
        self.SetStart(&parent, node.index())
    }

    // https://dom.spec.whatwg.org/#dom-range-setstartafter
    fn SetStartAfter(&self, node: &Node) -> ErrorResult {
        let parent = node.GetParentNode().ok_or(Error::InvalidNodeType)?;
        self.SetStart(&parent, node.index() + 1)
    }

    // https://dom.spec.whatwg.org/#dom-range-setendbefore
    fn SetEndBefore(&self, node: &Node) -> ErrorResult {
        let parent = node.GetParentNode().ok_or(Error::InvalidNodeType)?;
        self.SetEnd(&parent, node.index())
    }

    // https://dom.spec.whatwg.org/#dom-range-setendafter
    fn SetEndAfter(&self, node: &Node) -> ErrorResult {
        let parent = node.GetParentNode().ok_or(Error::InvalidNodeType)?;
        self.SetEnd(&parent, node.index() + 1)
    }

    // https://dom.spec.whatwg.org/#dom-range-collapse
    fn Collapse(&self, to_start: bool) {
        if to_start {
            self.set_end(&self.StartContainer(), self.StartOffset());
        } else {
            self.set_start(&self.EndContainer(), self.EndOffset());
        }
    }

    // https://dom.spec.whatwg.org/#dom-range-selectnode
    fn SelectNode(&self, node: &Node) -> ErrorResult {
        // Steps 1, 2.
        let parent = node.GetParentNode().ok_or(Error::InvalidNodeType)?;
        // Step 3.
        let index = node.index();
        // Step 4.
        self.set_start(&parent, index);
        // Step 5.
        self.set_end(&parent, index + 1);
        Ok(())
    }

    // https://dom.spec.whatwg.org/#dom-range-selectnodecontents
    fn SelectNodeContents(&self, node: &Node) -> ErrorResult {
        if node.is_doctype() {
            // Step 1.
            return Err(Error::InvalidNodeType);
        }
        // Step 2.
        let length = node.len();
        // Step 3.
        self.set_start(node, 0);
        // Step 4.
        self.set_end(node, length);
        Ok(())
    }

    // https://dom.spec.whatwg.org/#dom-range-compareboundarypoints
    fn CompareBoundaryPoints(&self, how: u16, other: &Range) -> Fallible<i16> {
        if how > RangeConstants::END_TO_START {
            // Step 1.
            return Err(Error::NotSupported);
        }
        let this_root = self
            .StartContainer()
            .inclusive_ancestors(ShadowIncluding::No)
            .last()
            .unwrap();
        let other_root = other
            .StartContainer()
            .inclusive_ancestors(ShadowIncluding::No)
            .last()
            .unwrap();
        if this_root != other_root {
            // Step 2.
            return Err(Error::WrongDocument);
        }
        // Step 3.
        let (this_point, other_point) = match how {
            RangeConstants::START_TO_START => (&self.start, &other.start),
            RangeConstants::START_TO_END => (&self.end, &other.start),
            RangeConstants::END_TO_END => (&self.end, &other.end),
            RangeConstants::END_TO_START => (&self.start, &other.end),
            _ => unreachable!(),
        };
        // step 4.
        match this_point.partial_cmp(other_point).unwrap() {
            Ordering::Less => Ok(-1),
            Ordering::Equal => Ok(0),
            Ordering::Greater => Ok(1),
        }
    }

    // https://dom.spec.whatwg.org/#dom-range-clonerange
    fn CloneRange(&self) -> DomRoot<Range> {
        let start_node = self.StartContainer();
        let owner_doc = start_node.owner_doc();
        Range::new(
            &owner_doc,
            &start_node,
            self.StartOffset(),
            &self.EndContainer(),
            self.EndOffset(),
        )
    }

    // https://dom.spec.whatwg.org/#dom-range-ispointinrange
    fn IsPointInRange(&self, node: &Node, offset: u32) -> Fallible<bool> {
        match self.compare_point(node, offset) {
            Ok(Ordering::Less) => Ok(false),
            Ok(Ordering::Equal) => Ok(true),
            Ok(Ordering::Greater) => Ok(false),
            Err(Error::WrongDocument) => {
                // Step 2.
                Ok(false)
            },
            Err(error) => Err(error),
        }
    }

    // https://dom.spec.whatwg.org/#dom-range-comparepoint
    fn ComparePoint(&self, node: &Node, offset: u32) -> Fallible<i16> {
        self.compare_point(node, offset).map(|order| match order {
            Ordering::Less => -1,
            Ordering::Equal => 0,
            Ordering::Greater => 1,
        })
    }

    // https://dom.spec.whatwg.org/#dom-range-intersectsnode
    fn IntersectsNode(&self, node: &Node) -> bool {
        let start_node = self.StartContainer();
        let start_node_root = self
            .StartContainer()
            .inclusive_ancestors(ShadowIncluding::No)
            .last()
            .unwrap();
        let node_root = node
            .inclusive_ancestors(ShadowIncluding::No)
            .last()
            .unwrap();
        if start_node_root != node_root {
            // Step 1.
            return false;
        }
        let parent = match node.GetParentNode() {
            Some(parent) => parent,
            None => {
                // Step 3.
                return true;
            },
        };
        // Step 4.
        let offset = node.index();
        // Step 5.
        Ordering::Greater ==
            bp_position(&parent, offset + 1, &start_node, self.StartOffset()).unwrap() &&
            Ordering::Less ==
                bp_position(&parent, offset, &self.EndContainer(), self.EndOffset()).unwrap()
    }

    // https://dom.spec.whatwg.org/#dom-range-clonecontents
    // https://dom.spec.whatwg.org/#concept-range-clone
    fn CloneContents(&self) -> Fallible<DomRoot<DocumentFragment>> {
        // Step 3.
        let start_node = self.StartContainer();
        let start_offset = self.StartOffset();
        let end_node = self.EndContainer();
        let end_offset = self.EndOffset();

        // Step 1.
        let fragment = DocumentFragment::new(&start_node.owner_doc());

        // Step 2.
        if self.start == self.end {
            return Ok(fragment);
        }

        if end_node == start_node {
            if let Some(cdata) = start_node.downcast::<CharacterData>() {
                // Steps 4.1-2.
                let data = cdata
                    .SubstringData(start_offset, end_offset - start_offset)
                    .unwrap();
                let clone = cdata.clone_with_data(data, &start_node.owner_doc());
                // Step 4.3.
                fragment.upcast::<Node>().AppendChild(&clone)?;
                // Step 4.4
                return Ok(fragment);
            }
        }

        // Steps 5-12.
        let (first_contained_child, last_contained_child, contained_children) =
            self.contained_children()?;

        if let Some(child) = first_contained_child {
            // Step 13.
            if let Some(cdata) = child.downcast::<CharacterData>() {
                assert!(child == start_node);
                // Steps 13.1-2.
                let data = cdata
                    .SubstringData(start_offset, start_node.len() - start_offset)
                    .unwrap();
                let clone = cdata.clone_with_data(data, &start_node.owner_doc());
                // Step 13.3.
                fragment.upcast::<Node>().AppendChild(&clone)?;
            } else {
                // Step 14.1.
                let clone = child.CloneNode(/* deep */ false)?;
                // Step 14.2.
                fragment.upcast::<Node>().AppendChild(&clone)?;
                // Step 14.3.
                let subrange = Range::new(
                    &clone.owner_doc(),
                    &start_node,
                    start_offset,
                    &child,
                    child.len(),
                );
                // Step 14.4.
                let subfragment = subrange.CloneContents()?;
                // Step 14.5.
                clone.AppendChild(subfragment.upcast())?;
            }
        }

        // Step 15.
        for child in contained_children {
            // Step 15.1.
            let clone = child.CloneNode(/* deep */ true)?;
            // Step 15.2.
            fragment.upcast::<Node>().AppendChild(&clone)?;
        }

        if let Some(child) = last_contained_child {
            // Step 16.
            if let Some(cdata) = child.downcast::<CharacterData>() {
                assert!(child == end_node);
                // Steps 16.1-2.
                let data = cdata.SubstringData(0, end_offset).unwrap();
                let clone = cdata.clone_with_data(data, &start_node.owner_doc());
                // Step 16.3.
                fragment.upcast::<Node>().AppendChild(&clone)?;
            } else {
                // Step 17.1.
                let clone = child.CloneNode(/* deep */ false)?;
                // Step 17.2.
                fragment.upcast::<Node>().AppendChild(&clone)?;
                // Step 17.3.
                let subrange = Range::new(&clone.owner_doc(), &child, 0, &end_node, end_offset);
                // Step 17.4.
                let subfragment = subrange.CloneContents()?;
                // Step 17.5.
                clone.AppendChild(subfragment.upcast())?;
            }
        }

        // Step 18.
        Ok(fragment)
    }

    // https://dom.spec.whatwg.org/#dom-range-extractcontents
    // https://dom.spec.whatwg.org/#concept-range-extract
    fn ExtractContents(&self) -> Fallible<DomRoot<DocumentFragment>> {
        // Step 3.
        let start_node = self.StartContainer();
        let start_offset = self.StartOffset();
        let end_node = self.EndContainer();
        let end_offset = self.EndOffset();

        // Step 1.
        let fragment = DocumentFragment::new(&start_node.owner_doc());

        // Step 2.
        if self.Collapsed() {
            return Ok(fragment);
        }

        if end_node == start_node {
            if let Some(end_data) = end_node.downcast::<CharacterData>() {
                // Step 4.1.
                let clone = end_node.CloneNode(/* deep */ true)?;
                // Step 4.2.
                let text = end_data.SubstringData(start_offset, end_offset - start_offset);
                clone
                    .downcast::<CharacterData>()
                    .unwrap()
                    .SetData(text.unwrap());
                // Step 4.3.
                fragment.upcast::<Node>().AppendChild(&clone)?;
                // Step 4.4.
                end_data.ReplaceData(start_offset, end_offset - start_offset, DOMString::new())?;
                // Step 4.5.
                return Ok(fragment);
            }
        }

        // Steps 5-12.
        let (first_contained_child, last_contained_child, contained_children) =
            self.contained_children()?;

        let (new_node, new_offset) = if start_node.is_inclusive_ancestor_of(&end_node) {
            // Step 13.
            (DomRoot::from_ref(&*start_node), start_offset)
        } else {
            // Step 14.1-2.
            let reference_node = start_node
                .ancestors()
                .take_while(|n| !n.is_inclusive_ancestor_of(&end_node))
                .last()
                .unwrap_or(DomRoot::from_ref(&start_node));
            // Step 14.3.
            (
                reference_node.GetParentNode().unwrap(),
                reference_node.index() + 1,
            )
        };

        if let Some(child) = first_contained_child {
            if let Some(start_data) = child.downcast::<CharacterData>() {
                assert!(child == start_node);
                // Step 15.1.
                let clone = start_node.CloneNode(/* deep */ true)?;
                // Step 15.2.
                let text = start_data.SubstringData(start_offset, start_node.len() - start_offset);
                clone
                    .downcast::<CharacterData>()
                    .unwrap()
                    .SetData(text.unwrap());
                // Step 15.3.
                fragment.upcast::<Node>().AppendChild(&clone)?;
                // Step 15.4.
                start_data.ReplaceData(
                    start_offset,
                    start_node.len() - start_offset,
                    DOMString::new(),
                )?;
            } else {
                // Step 16.1.
                let clone = child.CloneNode(/* deep */ false)?;
                // Step 16.2.
                fragment.upcast::<Node>().AppendChild(&clone)?;
                // Step 16.3.
                let subrange = Range::new(
                    &clone.owner_doc(),
                    &start_node,
                    start_offset,
                    &child,
                    child.len(),
                );
                // Step 16.4.
                let subfragment = subrange.ExtractContents()?;
                // Step 16.5.
                clone.AppendChild(subfragment.upcast())?;
            }
        }

        // Step 17.
        for child in contained_children {
            fragment.upcast::<Node>().AppendChild(&child)?;
        }

        if let Some(child) = last_contained_child {
            if let Some(end_data) = child.downcast::<CharacterData>() {
                assert!(child == end_node);
                // Step 18.1.
                let clone = end_node.CloneNode(/* deep */ true)?;
                // Step 18.2.
                let text = end_data.SubstringData(0, end_offset);
                clone
                    .downcast::<CharacterData>()
                    .unwrap()
                    .SetData(text.unwrap());
                // Step 18.3.
                fragment.upcast::<Node>().AppendChild(&clone)?;
                // Step 18.4.
                end_data.ReplaceData(0, end_offset, DOMString::new())?;
            } else {
                // Step 19.1.
                let clone = child.CloneNode(/* deep */ false)?;
                // Step 19.2.
                fragment.upcast::<Node>().AppendChild(&clone)?;
                // Step 19.3.
                let subrange = Range::new(&clone.owner_doc(), &child, 0, &end_node, end_offset);
                // Step 19.4.
                let subfragment = subrange.ExtractContents()?;
                // Step 19.5.
                clone.AppendChild(subfragment.upcast())?;
            }
        }

        // Step 20.
        self.SetStart(&new_node, new_offset)?;
        self.SetEnd(&new_node, new_offset)?;

        // Step 21.
        Ok(fragment)
    }

    // https://dom.spec.whatwg.org/#dom-range-detach
    fn Detach(&self) {
        // This method intentionally left blank.
    }

    // https://dom.spec.whatwg.org/#dom-range-insertnode
    // https://dom.spec.whatwg.org/#concept-range-insert
    fn InsertNode(&self, node: &Node) -> ErrorResult {
        let start_node = self.StartContainer();
        let start_offset = self.StartOffset();

        // Step 1.
        if &*start_node == node {
            return Err(Error::HierarchyRequest);
        }
        match start_node.type_id() {
            // Handled under step 2.
            NodeTypeId::CharacterData(CharacterDataTypeId::Text(_)) => (),
            NodeTypeId::CharacterData(_) => return Err(Error::HierarchyRequest),
            _ => (),
        }

        // Step 2.
        let (reference_node, parent) = match start_node.type_id() {
            NodeTypeId::CharacterData(CharacterDataTypeId::Text(_)) => {
                // Step 3.
                let parent = match start_node.GetParentNode() {
                    Some(parent) => parent,
                    // Step 1.
                    None => return Err(Error::HierarchyRequest),
                };
                // Step 5.
                (Some(DomRoot::from_ref(&*start_node)), parent)
            },
            _ => {
                // Steps 4-5.
                let child = start_node.ChildNodes().Item(start_offset);
                (child, DomRoot::from_ref(&*start_node))
            },
        };

        // Step 6.
        Node::ensure_pre_insertion_validity(node, &parent, reference_node.as_deref())?;

        // Step 7.
        let split_text;
        let reference_node = match start_node.downcast::<Text>() {
            Some(text) => {
                split_text = text.SplitText(start_offset)?;
                let new_reference = DomRoot::upcast::<Node>(split_text);
                assert!(new_reference.GetParentNode().as_deref() == Some(&parent));
                Some(new_reference)
            },
            _ => reference_node,
        };

        // Step 8.
        let reference_node = if Some(node) == reference_node.as_deref() {
            node.GetNextSibling()
        } else {
            reference_node
        };

        // Step 9.
        node.remove_self();

        // Step 10.
        let new_offset = reference_node
            .as_ref()
            .map_or(parent.len(), |node| node.index());

        // Step 11
        let new_offset = new_offset +
            if let NodeTypeId::DocumentFragment(_) = node.type_id() {
                node.len()
            } else {
                1
            };

        // Step 12.
        Node::pre_insert(node, &parent, reference_node.as_deref())?;

        // Step 13.
        if self.Collapsed() {
            self.set_end(&parent, new_offset);
        }

        Ok(())
    }

    // https://dom.spec.whatwg.org/#dom-range-deletecontents
    fn DeleteContents(&self) -> ErrorResult {
        // Step 1.
        if self.Collapsed() {
            return Ok(());
        }

        // Step 2.
        let start_node = self.StartContainer();
        let end_node = self.EndContainer();
        let start_offset = self.StartOffset();
        let end_offset = self.EndOffset();

        // Step 3.
        if start_node == end_node {
            if let Some(text) = start_node.downcast::<CharacterData>() {
                if end_offset > start_offset {
                    self.report_change();
                }
                return text.ReplaceData(start_offset, end_offset - start_offset, DOMString::new());
            }
        }

        // Step 4.
        rooted_vec!(let mut contained_children);
        let ancestor = self.CommonAncestorContainer();

        let mut iter = start_node.following_nodes(&ancestor);

        let mut next = iter.next();
        while let Some(child) = next {
            if self.contains(&child) {
                contained_children.push(Dom::from_ref(&*child));
                next = iter.next_skipping_children();
            } else {
                next = iter.next();
            }
        }

        let (new_node, new_offset) = if start_node.is_inclusive_ancestor_of(&end_node) {
            // Step 5.
            (DomRoot::from_ref(&*start_node), start_offset)
        } else {
            // Step 6.
            fn compute_reference(start_node: &Node, end_node: &Node) -> (DomRoot<Node>, u32) {
                let mut reference_node = DomRoot::from_ref(start_node);
                while let Some(parent) = reference_node.GetParentNode() {
                    if parent.is_inclusive_ancestor_of(end_node) {
                        return (parent, reference_node.index() + 1);
                    }
                    reference_node = parent;
                }
                unreachable!()
            }

            compute_reference(&start_node, &end_node)
        };

        // Step 7.
        if let Some(text) = start_node.downcast::<CharacterData>() {
            text.ReplaceData(
                start_offset,
                start_node.len() - start_offset,
                DOMString::new(),
            )
            .unwrap();
        }

        // Step 8.
        for child in &*contained_children {
            child.remove_self();
        }

        // Step 9.
        if let Some(text) = end_node.downcast::<CharacterData>() {
            text.ReplaceData(0, end_offset, DOMString::new()).unwrap();
        }

        // Step 10.
        self.SetStart(&new_node, new_offset).unwrap();
        self.SetEnd(&new_node, new_offset).unwrap();
        Ok(())
    }

    // https://dom.spec.whatwg.org/#dom-range-surroundcontents
    fn SurroundContents(&self, new_parent: &Node) -> ErrorResult {
        // Step 1.
        let start = self.StartContainer();
        let end = self.EndContainer();

        if start
            .inclusive_ancestors(ShadowIncluding::No)
            .any(|n| !n.is_inclusive_ancestor_of(&end) && !n.is::<Text>()) ||
            end.inclusive_ancestors(ShadowIncluding::No)
                .any(|n| !n.is_inclusive_ancestor_of(&start) && !n.is::<Text>())
        {
            return Err(Error::InvalidState);
        }

        // Step 2.
        match new_parent.type_id() {
            NodeTypeId::Document(_) |
            NodeTypeId::DocumentType |
            NodeTypeId::DocumentFragment(_) => {
                return Err(Error::InvalidNodeType);
            },
            _ => (),
        }

        // Step 3.
        let fragment = self.ExtractContents()?;

        // Step 4.
        Node::replace_all(None, new_parent);

        // Step 5.
        self.InsertNode(new_parent)?;

        // Step 6.
        new_parent.AppendChild(fragment.upcast())?;

        // Step 7.
        self.SelectNode(new_parent)
    }

    // https://dom.spec.whatwg.org/#dom-range-stringifier
    fn Stringifier(&self) -> DOMString {
        let start_node = self.StartContainer();
        let end_node = self.EndContainer();

        // Step 1.
        let mut s = DOMString::new();

        if let Some(text_node) = start_node.downcast::<Text>() {
            let char_data = text_node.upcast::<CharacterData>();

            // Step 2.
            if start_node == end_node {
                return char_data
                    .SubstringData(self.StartOffset(), self.EndOffset() - self.StartOffset())
                    .unwrap();
            }

            // Step 3.
            s.push_str(
                &*char_data
                    .SubstringData(self.StartOffset(), char_data.Length() - self.StartOffset())
                    .unwrap(),
            );
        }

        // Step 4.
        let ancestor = self.CommonAncestorContainer();
        let mut iter = start_node
            .following_nodes(&ancestor)
            .filter_map(DomRoot::downcast::<Text>);

        while let Some(child) = iter.next() {
            if self.contains(child.upcast()) {
                s.push_str(&*child.upcast::<CharacterData>().Data());
            }
        }

        // Step 5.
        if let Some(text_node) = end_node.downcast::<Text>() {
            let char_data = text_node.upcast::<CharacterData>();
            s.push_str(&*char_data.SubstringData(0, self.EndOffset()).unwrap());
        }

        // Step 6.
        s
    }

    // https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#extensions-to-the-range-interface
    fn CreateContextualFragment(&self, fragment: DOMString) -> Fallible<DomRoot<DocumentFragment>> {
        // Step 1.
        let node = self.StartContainer();
        let owner_doc = node.owner_doc();
        let element = match node.type_id() {
            NodeTypeId::Document(_) | NodeTypeId::DocumentFragment(_) => None,
            NodeTypeId::Element(_) => Some(DomRoot::downcast::<Element>(node).unwrap()),
            NodeTypeId::CharacterData(CharacterDataTypeId::Comment) |
            NodeTypeId::CharacterData(CharacterDataTypeId::Text(_)) => node.GetParentElement(),
            NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) |
            NodeTypeId::DocumentType => unreachable!(),
            NodeTypeId::Attr => unreachable!(),
        };

        // Step 2.
        let element = Element::fragment_parsing_context(&owner_doc, element.as_deref());

        // Step 3.
        let fragment_node = element.parse_fragment(fragment)?;

        // Step 4.
        for node in fragment_node
            .upcast::<Node>()
            .traverse_preorder(ShadowIncluding::No)
        {
            if let Some(script) = node.downcast::<HTMLScriptElement>() {
                script.set_already_started(false);
                script.set_parser_inserted(false);
            }
        }

        // Step 5.
        Ok(fragment_node)
    }
}

#[derive(DenyPublicFields, JSTraceable, MallocSizeOf)]
#[unrooted_must_root_lint::must_root]
pub struct BoundaryPoint {
    node: MutDom<Node>,
    offset: Cell<u32>,
}

impl BoundaryPoint {
    fn new(node: &Node, offset: u32) -> BoundaryPoint {
        debug_assert!(!node.is_doctype());
        debug_assert!(offset <= node.len());
        BoundaryPoint {
            node: MutDom::new(node),
            offset: Cell::new(offset),
        }
    }

    pub fn set(&self, node: &Node, offset: u32) {
        self.node.set(node);
        self.set_offset(offset);
    }

    pub fn set_offset(&self, offset: u32) {
        self.offset.set(offset);
    }
}

#[allow(unrooted_must_root)]
impl PartialOrd for BoundaryPoint {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        bp_position(
            &self.node.get(),
            self.offset.get(),
            &other.node.get(),
            other.offset.get(),
        )
    }
}

#[allow(unrooted_must_root)]
impl PartialEq for BoundaryPoint {
    fn eq(&self, other: &Self) -> bool {
        self.node.get() == other.node.get() && self.offset.get() == other.offset.get()
    }
}

// https://dom.spec.whatwg.org/#concept-range-bp-position
fn bp_position(a_node: &Node, a_offset: u32, b_node: &Node, b_offset: u32) -> Option<Ordering> {
    if a_node as *const Node == b_node as *const Node {
        // Step 1.
        return Some(a_offset.cmp(&b_offset));
    }
    let position = b_node.CompareDocumentPosition(a_node);
    if position & NodeConstants::DOCUMENT_POSITION_DISCONNECTED != 0 {
        // No order is defined for nodes not in the same tree.
        None
    } else if position & NodeConstants::DOCUMENT_POSITION_FOLLOWING != 0 {
        // Step 2.
        match bp_position(b_node, b_offset, a_node, a_offset).unwrap() {
            Ordering::Less => Some(Ordering::Greater),
            Ordering::Greater => Some(Ordering::Less),
            Ordering::Equal => unreachable!(),
        }
    } else if position & NodeConstants::DOCUMENT_POSITION_CONTAINS != 0 {
        // Step 3-1, 3-2.
        let mut b_ancestors = b_node.inclusive_ancestors(ShadowIncluding::No);
        let child = b_ancestors
            .find(|child| &*child.GetParentNode().unwrap() == a_node)
            .unwrap();
        // Step 3-3.
        if child.index() < a_offset {
            Some(Ordering::Greater)
        } else {
            // Step 4.
            Some(Ordering::Less)
        }
    } else {
        // Step 4.
        Some(Ordering::Less)
    }
}

pub struct WeakRangeVec {
    cell: UnsafeCell<WeakRefVec<Range>>,
}

#[allow(unsafe_code)]
impl WeakRangeVec {
    /// Create a new vector of weak references.
    pub fn new() -> Self {
        WeakRangeVec {
            cell: UnsafeCell::new(WeakRefVec::new()),
        }
    }

    /// Whether that vector of ranges is empty.
    pub fn is_empty(&self) -> bool {
        unsafe { (*self.cell.get()).is_empty() }
    }

    /// Used for steps 2.1-2. when inserting a node.
    /// <https://dom.spec.whatwg.org/#concept-node-insert>
    pub fn increase_above(&self, node: &Node, offset: u32, delta: u32) {
        self.map_offset_above(node, offset, |offset| offset + delta);
    }

    /// Used for steps 4-5. when removing a node.
    /// <https://dom.spec.whatwg.org/#concept-node-remove>
    pub fn decrease_above(&self, node: &Node, offset: u32, delta: u32) {
        self.map_offset_above(node, offset, |offset| offset - delta);
    }

    /// Used for steps 2-3. when removing a node.
    /// <https://dom.spec.whatwg.org/#concept-node-remove>
    pub fn drain_to_parent(&self, context: &UnbindContext, child: &Node) {
        if self.is_empty() {
            return;
        }

        let offset = context.index();
        let parent = context.parent;
        unsafe {
            let ranges = &mut *self.cell.get();

            ranges.update(|entry| {
                let range = entry.root().unwrap();
                if &range.start.node == parent || &range.end.node == parent {
                    entry.remove();
                }
                if &range.start.node == child {
                    range.report_change();
                    range.start.set(context.parent, offset);
                }
                if &range.end.node == child {
                    range.report_change();
                    range.end.set(context.parent, offset);
                }
            });

            (*context.parent.ranges().cell.get()).extend(ranges.drain(..));
        }
    }

    /// Used for steps 7.1-2. when normalizing a node.
    /// <https://dom.spec.whatwg.org/#dom-node-normalize>
    pub fn drain_to_preceding_text_sibling(&self, node: &Node, sibling: &Node, length: u32) {
        if self.is_empty() {
            return;
        }

        unsafe {
            let ranges = &mut *self.cell.get();

            ranges.update(|entry| {
                let range = entry.root().unwrap();
                if &range.start.node == sibling || &range.end.node == sibling {
                    entry.remove();
                }
                if &range.start.node == node {
                    range.report_change();
                    range.start.set(sibling, range.StartOffset() + length);
                }
                if &range.end.node == node {
                    range.report_change();
                    range.end.set(sibling, range.EndOffset() + length);
                }
            });

            (*sibling.ranges().cell.get()).extend(ranges.drain(..));
        }
    }

    /// Used for steps 7.3-4. when normalizing a node.
    /// <https://dom.spec.whatwg.org/#dom-node-normalize>
    pub fn move_to_text_child_at(&self, node: &Node, offset: u32, child: &Node, new_offset: u32) {
        unsafe {
            let child_ranges = &mut *child.ranges().cell.get();

            (*self.cell.get()).update(|entry| {
                let range = entry.root().unwrap();

                let node_is_start = &range.start.node == node;
                let node_is_end = &range.end.node == node;

                let move_start = node_is_start && range.StartOffset() == offset;
                let move_end = node_is_end && range.EndOffset() == offset;

                let remove_from_node = move_start && move_end ||
                    move_start && !node_is_end ||
                    move_end && !node_is_start;

                let already_in_child = &range.start.node == child || &range.end.node == child;
                let push_to_child = !already_in_child && (move_start || move_end);

                if remove_from_node {
                    let ref_ = entry.remove();
                    if push_to_child {
                        child_ranges.push(ref_);
                    }
                } else if push_to_child {
                    child_ranges.push(WeakRef::new(&range));
                }

                if move_start {
                    range.report_change();
                    range.start.set(child, new_offset);
                }
                if move_end {
                    range.report_change();
                    range.end.set(child, new_offset);
                }
            });
        }
    }

    /// Used for steps 8-11. when replacing character data.
    /// <https://dom.spec.whatwg.org/#concept-cd-replace>
    pub fn replace_code_units(
        &self,
        node: &Node,
        offset: u32,
        removed_code_units: u32,
        added_code_units: u32,
    ) {
        self.map_offset_above(node, offset, |range_offset| {
            if range_offset <= offset + removed_code_units {
                offset
            } else {
                range_offset + added_code_units - removed_code_units
            }
        });
    }

    /// Used for steps 7.2-3. when splitting a text node.
    /// <https://dom.spec.whatwg.org/#concept-text-split>
    pub fn move_to_following_text_sibling_above(&self, node: &Node, offset: u32, sibling: &Node) {
        unsafe {
            let sibling_ranges = &mut *sibling.ranges().cell.get();

            (*self.cell.get()).update(|entry| {
                let range = entry.root().unwrap();
                let start_offset = range.StartOffset();
                let end_offset = range.EndOffset();

                let node_is_start = &range.start.node == node;
                let node_is_end = &range.end.node == node;

                let move_start = node_is_start && start_offset > offset;
                let move_end = node_is_end && end_offset > offset;

                let remove_from_node = move_start && move_end ||
                    move_start && !node_is_end ||
                    move_end && !node_is_start;

                let already_in_sibling = &range.start.node == sibling || &range.end.node == sibling;
                let push_to_sibling = !already_in_sibling && (move_start || move_end);

                if remove_from_node {
                    let ref_ = entry.remove();
                    if push_to_sibling {
                        sibling_ranges.push(ref_);
                    }
                } else if push_to_sibling {
                    sibling_ranges.push(WeakRef::new(&range));
                }

                if move_start {
                    range.report_change();
                    range.start.set(sibling, start_offset - offset);
                }
                if move_end {
                    range.report_change();
                    range.end.set(sibling, end_offset - offset);
                }
            });
        }
    }

    /// Used for steps 7.4-5. when splitting a text node.
    /// <https://dom.spec.whatwg.org/#concept-text-split>
    pub fn increment_at(&self, node: &Node, offset: u32) {
        unsafe {
            (*self.cell.get()).update(|entry| {
                let range = entry.root().unwrap();
                if &range.start.node == node && offset == range.StartOffset() {
                    range.report_change();
                    range.start.set_offset(offset + 1);
                }
                if &range.end.node == node && offset == range.EndOffset() {
                    range.report_change();
                    range.end.set_offset(offset + 1);
                }
            });
        }
    }

    fn map_offset_above<F: FnMut(u32) -> u32>(&self, node: &Node, offset: u32, mut f: F) {
        unsafe {
            (*self.cell.get()).update(|entry| {
                let range = entry.root().unwrap();
                let start_offset = range.StartOffset();
                if &range.start.node == node && start_offset > offset {
                    range.report_change();
                    range.start.set_offset(f(start_offset));
                }
                let end_offset = range.EndOffset();
                if &range.end.node == node && end_offset > offset {
                    range.report_change();
                    range.end.set_offset(f(end_offset));
                }
            });
        }
    }

    fn push(&self, ref_: WeakRef<Range>) {
        unsafe {
            (*self.cell.get()).push(ref_);
        }
    }

    fn remove(&self, range: &Range) -> WeakRef<Range> {
        unsafe {
            let ranges = &mut *self.cell.get();
            let position = ranges.iter().position(|ref_| ref_ == range).unwrap();
            ranges.swap_remove(position)
        }
    }
}

#[allow(unsafe_code)]
impl MallocSizeOf for WeakRangeVec {
    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
        unsafe { (*self.cell.get()).size_of(ops) }
    }
}

#[allow(unsafe_code)]
unsafe impl JSTraceable for WeakRangeVec {
    unsafe fn trace(&self, _: *mut JSTracer) {
        (*self.cell.get()).retain_alive()
    }
}