an-rope 0.3.1

an rope for large text documents.
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
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
//! # An rope.
//!
//! An immutable Rope data structure for storing large text documents. This
//! implementation is a component of the [`an-editor`]
//! project.
//!
//! A rope is an efficient data structure for large strings. It's
//! essentially a binary tree whose leaves are strings.
//!
//! For more information, see the following resources:
//!
//! + http://scienceblogs.com/goodmath/2009/01/26/ropes-twining-together-strings/
//! + https://www.ibm.com/developerworks/library/j-ropes/
//! + http://citeseer.ist.psu.edu/viewdoc/download?doi=10.1.1.14.9450&rep=rep1&type=pdf
//! [`an-editor`]: https://github.com/an-cabal/an-editor

#![cfg_attr( feature = "unstable"
           , feature( const_fn
                    , box_syntax, box_patterns
                    , conservative_impl_trait
                    , collections, collections_range
                    , inclusive_range_syntax
                    ))]
#![cfg_attr( all( test, feature = "unstable")
           , feature( test, insert_str) )]
#![cfg_attr( feature = "clippy", feature(plugin) )]
#![cfg_attr( feature = "clippy", plugin(clippy) )]
#![cfg_attr( feature = "clippy", allow(unused_variables, dead_code))]

#[macro_use] extern crate macro_attr;
#[macro_use] extern crate newtype_derive;

#[cfg(feature = "unstable")] extern crate collections;
#[cfg(feature = "unstable")] use collections::range::RangeArgument;

extern crate unicode_segmentation;

use std::cmp;
use std::ops;
use std::convert;
use std::fmt;
use std::string;
use std::iter;

macro_rules! or_zero {
    ($a: expr, $b: expr) => { if $a > $b { $a - $b } else { 0 } }
}

#[cfg(feature = "tendril")] extern crate tendril;

#[cfg(test)] #[macro_use] extern crate quickcheck;
#[cfg(test)] mod test;
#[cfg(all( test, feature = "unstable"))] mod bench;

mod unicode;
pub mod metric;

use metric::{Measured, Metric};
use self::internals::{Node, NodeLink};

pub use self::slice::{ RopeSlice
                    //, RopeSliceMut
                        };

impl<T> convert::From<T> for Rope
where T: convert::Into<NodeLink> {
    #[inline] fn from(that: T) -> Self {
        Rope { root: that.into().rebalance() }
    }
}

/// A Rope
///
/// This Rope implementation aims to eventually function as a superset of
/// [`String`](https://doc.rust-lang.org/1.3.0/std/string/struct.String.html),
/// providing the same API plus additional methods. Therefore, code which uses
/// `String` can easily be ported to use `Rope`.
///
/// `Rope` provides two APIs for editing a `Rope`: a destructive,
/// append-in-place API whose methods match those of `String`, and a
/// non-destructive, persistant API. The persistant API's methods have names
/// prefixed with ``, such as `push()` and `append()`.
///
#[derive(Clone, Default)]
pub struct Rope {
    // can we get away with having these be of &str or will they need
    // to be string?
    root: NodeLink
}

pub trait Split: Sized {
    fn split<M>(&self, index: M) -> (Self,Self)
    where M: Metric
        , Self: Measured<M>;
}

impl<M> Measured<M> for Rope
where M: Metric
    , NodeLink: Measured<M>
    , String: Measured<M>
    {

    #[inline] fn to_byte_index(&self, index: M) -> Option<usize> {
        self.root.to_byte_index(index)
    }

    #[inline] fn measure(&self) -> M { self.root.measure() }

    #[inline] fn measure_weight(&self) -> M { self.root.measure_weight() }

}

impl fmt::Debug for Rope {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Rope[\"{}\"] {:?}", self.root, self.root)
    }
}

impl fmt::Display for Rope {

    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.root)
    }
}
 #[cfg(feature = "unstable")]
macro_rules! unstable_iters {
    ( $($(#[$attr:meta])*
     pub fn $name:ident$(<$lf:tt>)*(&'a $sel:ident) -> $ty:ty {
         $body:expr
     })+ ) => { $(
         $(#[$attr])*
         #[cfg_attr(feature = "clippy", allow(needless_lifetimes))]
         pub fn $name$(<$lf>)*(&'a $sel) -> $ty {
             $body
         }
    )+ };
    ( $($(#[$attr:meta])*
    pub fn $name:ident$(<$lf:tt>)*(&'a mut $sel:ident) -> $ty:ty {
         $body:expr
     })+ ) => { $(
         $(#[$attr])*
         #[cfg(feature = "unstable")]
         #[cfg_attr(feature = "clippy", allow(needless_lifetimes))]
         pub fn $name$(<$lf>)*(&'a mut $sel) -> $ty {
             $body
         }
    )+ };
}

#[cfg(not(feature = "unstable"))]
macro_rules! unstable_iters {
    ( $($(#[$attr:meta])*
    pub fn $name:ident$(<$lf:tt>)*(&'a $sel:ident) -> impl Iterator<Item=$ty:ty> + 'a {
         $body:expr
     })+ ) => ($(
         $(#[$attr])*
         #[cfg(not(feature = "unstable"))]
         #[cfg_attr(feature = "clippy", allow(needless_lifetimes))]
         pub fn $name$(<$lf>)*(&'a $sel) -> Box<Iterator<Item=$ty> + 'a> {
             Box::new($body)
         }
     )+);
    ( $( $(#[$attr:meta])*
    pub fn $name:ident$(<$lf:tt>)*(&'a mut $sel:ident) - impl Iterator<Item=$ty:ty> + 'a {
         $body:expr
     })+ ) => { $({
         $(#[$attr])*
         #[cfg(not(feature = "unstable"))]
         #[cfg_attr(feature = "clippy", allow(needless_lifetimes))]
         pub fn $name$(<$lf>)*(&'a mut $sel) -> Box<Iterator<Item=$ty> + 'a> {
             Box::new($body)
         }
     })+
    };
}
macro_rules! str_iters {
    ( $($(#[$attr:meta])* impl $name: ident<$ty: ty> for Node {})+ ) => { $(
        unstable_iters! {
            $(#[$attr])*
            pub fn $name<'a>(&'a self) -> impl Iterator<Item=$ty> + 'a{
                self.strings().flat_map(str::$name)
            }
        }
    )+ };

    ( $($(#[$attr:meta])* impl $name: ident<$ty: ty> for Rope {})+ )=> { $(
        unstable_iters! {
            $(#[$attr])*
            pub fn $name<'a>(&'a self) -> impl Iterator<Item=$ty>  + 'a{
                self.root.$name()
            }
        }
    )+ }

}


macro_rules! unicode_seg_iters {
    ( $($(#[$attr:meta])* impl $name: ident for Node { extend })+ ) => { $(

        unstable_iters! {
            $(#[$attr])*
            pub fn $name<'a>(&'a self) -> impl Iterator<Item=&'a str> + 'a {
                { // this block is required so that the macro will bind the
                  // `use` statement
                    use unicode_segmentation::UnicodeSegmentation;
                    self.strings()
                        .flat_map(|s| UnicodeSegmentation::$name(s, true))
                }
            }
        }
    )+ };
    ( $($(#[$attr:meta])* impl $name: ident for Node {} )+ ) => { $(
        unstable_iters!{
            $(#[$attr])*
            pub fn $name<'a>(&'a self) -> impl Iterator<Item=&'a str> + 'a {
                { // this block is required so that the macro will bind the
                  // `use` statement
                    use unicode_segmentation::UnicodeSegmentation;
                    self.strings().flat_map(UnicodeSegmentation::$name)
                }
            }
        }
    )+ };
    ( $($(#[$attr:meta])* impl $name: ident<$ty: ty> for Rope {})+ )=> { $(
        unstable_iters! {
            $(#[$attr])*
            pub fn $name<'a>(&'a self) -> impl Iterator<Item=$ty> + 'a {
                self.root.$name()
            }
        }
    )+ }

}

mod internals;
mod slice;

impl Rope {

    /// Converts a vector of bytes to a `Rope`.
    ///
    /// If you are sure that the byte slice is valid UTF-8, and you don't want
    /// to incur the overhead of the validity check, there is an unsafe version
    /// of this function, `from_utf8_unchecked(),`` which has the same behavior
    /// but skips the check.
    ///
    /// This method will take care to not copy the vector, for efficiency's
    /// sake.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the slice is not UTF-8 with a description as to why the
    /// provided bytes are not UTF-8. The vector you moved in is also included.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use an_rope::Rope;
    ///
    /// // some bytes, in a vector
    /// let sparkle_heart = vec![240, 159, 146, 150];
    ///
    /// // We know these bytes are valid, so we'll use `unwrap()`.
    /// let sparkle_heart = Rope::from_utf8(sparkle_heart).unwrap();
    ///
    /// assert_eq!(&sparkle_heart, "💖");
    /// ```
    ///
    /// Incorrect bytes:
    ///
    /// ```
    /// use an_rope::Rope;
    ///
    /// // some invalid bytes, in a vector
    /// let sparkle_heart = vec![0, 159, 146, 150];
    ///
    /// assert!(Rope::from_utf8(sparkle_heart).is_err());
    /// ```
    ///
    #[inline]
    pub fn from_utf8(vec: Vec<u8>) -> Result<Rope, string::FromUtf8Error> {
        String::from_utf8(vec).map(Rope::from)
    }

    /// Decode a UTF-16 encoded vector `v` into a `Rope`,
    /// returning `Err` if `v` contains any invalid data.
    #[inline]
    pub fn from_utf16(v: &[u16]) -> Result<Rope, string::FromUtf16Error> {
        String::from_utf16(v).map(Rope::from)
    }

    /// Converts a vector of bytes to a `Rope` without checking that the
    /// vector contains valid UTF-8.
    ///
    /// See the safe version, [`from_utf8()`], for more details.
    ///
    /// [`from_utf8()`]: struct.Rope.html#method.from_utf8
    ///
    /// # Safety
    ///
    /// This function is unsafe because it does not check that the bytes passed
    /// to it are valid UTF-8. If this constraint is violated, it may cause
    /// memory unsafety issues with future users of the `Rope`, as the rest of
    /// the standard library assumes that `Rope`s are valid UTF-8.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use an_rope::Rope;
    ///
    /// // some bytes, in a vector
    /// let sparkle_heart = vec![240, 159, 146, 150];
    ///
    /// let sparkle_heart = unsafe {
    ///     Rope::from_utf8_unchecked(sparkle_heart)
    /// };
    ///
    /// assert_eq!(&sparkle_heart, "💖");
    /// ```
    #[inline]
    pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> Rope {
        Rope::from(String::from_utf8_unchecked(bytes))
    }

    /// Returns a new empty Rope
    ///
    /// # Examples
    /// ```
    /// use an_rope::Rope;
    /// let mut an_rope = Rope::new();
    /// assert_eq!(an_rope.len(), 0);
    /// ```
    #[inline] pub fn new() -> Rope { Rope::from(Node::empty()) }

    /// Returns the length of this Rope
    ///
    /// # Examples
    ///
    /// An empty `Rope` should have length 0.
    ///
    /// ```
    /// use an_rope::Rope;
    /// let mut an_empty_rope = Rope::new();
    /// assert_eq!(an_empty_rope.len(), 0);
    /// ```
    ///
    /// ```
    /// use an_rope::Rope;
    /// let mut an_empty_rope = Rope::from(String::from(""));
    /// assert_eq!(an_empty_rope.len(), 0);
    /// ```
    ///
    /// A `Rope` with text should have length equal to the number of
    /// characters in the `Rope`.
    ///
    /// ```
    /// use an_rope::Rope;
    /// let mut an_rope = Rope::from(String::from("a string"));
    /// assert_eq!(an_rope.len(), "a string".len());
    /// ```
    pub fn len(&self) -> usize { self.root.len() }

    /// Returns `true` if this `Rope` is empty.
    ///
    /// # Examples
    ///
    /// A `Rope` with no characters should be empty:
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_empty_rope = Rope::new();
    /// assert!(an_empty_rope.is_empty());
    /// ```
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_empty_rope = Rope::from(String::from(""));
    /// assert!(an_empty_rope.is_empty());
    /// ```
    ///
    /// A `Rope` with characters should not be empty:
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("a string");
    /// assert!(!an_rope.is_empty());
    /// ```
    #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 }

    /// Insert `ch` into `index` in this `Rope`, returning a new `Rope`.
    ///
    ///
    /// # Returns
    /// * A new `Rope` with `ch` inserted at `index`
    ///
    /// # Time Complexity
    /// O(log _n_)
    ///
    /// # Panics
    /// * If `index` is greater than the length of this `Rope`
    ///
    /// # Examples
    ///
    /// Inserting at index 0 prepends `rope` to this `Rope`:
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("bcd");
    /// let new_rope = an_rope.insert(0, 'a');
    /// assert_eq!(new_rope, Rope::from("abcd"));
    /// assert_eq!(an_rope, Rope::from("bcd"));
    /// ```
    ///
    /// Inserting at index `len` prepends `char` to this `Rope`:
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("abc");
    /// let new_rope = an_rope.insert(an_rope.len(), 'd');
    /// assert_eq!(new_rope, Rope::from("abcd"));
    /// assert_eq!(an_rope, Rope::from("abc"));
    /// ```
    ///
    /// Inserting at an index in the middle inserts `char` at that index:
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("acd");
    /// let new_rope = an_rope.insert(1, 'b');
    /// assert_eq!(new_rope, Rope::from("abcd"));
    /// assert_eq!(an_rope, Rope::from("acd"));
    /// ```
    #[inline]
    #[inline]
    pub fn insert<M>(&self, index: M, ch: char) -> Rope
    where M: Metric
        , Self: Measured<M>
        , NodeLink: Measured<M>
        , String: Measured<M>
        , str: Measured<M>
        {
        assert!( index <= self.measure()
               , "Rope::insert: index {:?} was > length {:?}"
               , index, self.measure());
        // TODO: this is gross...
        let mut s = String::new();
        s.push(ch);
        self.insert_rope(index, &Rope::from(s))
    }



    /// Delete the range `range` from this `Rope`,
    ///
    /// # Panics
    /// * If the start or end of `range` are indices outside of the `Rope`
    /// * If the end index of `range` is greater than the start index
    ///
    /// # Time Complexity
    /// O(log _n_)
    ///
    /// # Examples
    ///
    /// Deleting "not" from this `Rope`:
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("this is not fine".to_string());
    /// let an_rope = an_rope.delete((8..12));
    /// assert_eq!(&an_rope, "this is fine");
    /// ```
    #[inline]
    #[cfg(feature = "unstable")]
    pub fn delete<R, M>(&self, range: R) -> Rope
    where R: RangeArgument<M>
        , M: Metric
        , Rope: Measured<M>
        , NodeLink: Measured<M>
        , String: Measured<M>
        , str: Measured<M>
        {
        let start = range.start().map(|s| *s)
                         .unwrap_or_else(|| { M::default() });
        let end = range.end().map(|e| *e)
                       .unwrap_or_else(|| { self.measure() });

        assert!( start <= end
               , "invalid index! start {:?} > end {:?}", end, start);
        let (l, r) = self.root.split(start);
        let (_, r) = r.split(end - start);
        Rope::from(Node::new_branch(l, r))
    }

    #[inline]
    #[cfg(not(feature = "unstable"))]
    pub fn delete<M: Metric>(&self, range: ops::Range<M>) -> Rope
    where NodeLink: Measured<M>
        , String: Measured<M>
        , str: Measured<M>
        {
        let (l, r) = self.root.split(range.start);
        let (_, r) = r.split(range.end - range.start);
        Rope::from(Node::new_branch(l, r))
    }


    /// Insert `rope` into `index` in this `Rope`, returning a new `Rope`.
    ///
    /// # Returns
    /// * A new `Rope` with `rope` inserted at `index`
    ///
    /// # Time Complexity
    /// O(log _n_)
    ///
    /// # Panics
    /// * If `index` is greater than the length of this `Rope`
    ///
    /// # Examples
    ///
    /// Inserting at index 0 prepends `rope` to this `Rope`:
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("cd");
    /// let new_rope = an_rope.insert_rope(0, &Rope::from("ab"));
    /// assert_eq!(new_rope, Rope::from("abcd"));
    /// assert_eq!(an_rope, Rope::from("cd"));
    /// ```
    ///
    /// Inserting at index `len` prepends `rope` to this `Rope`:
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("ab");
    /// let new_rope = an_rope.insert_rope(an_rope.len(), &Rope::from("cd"));
    /// assert_eq!(new_rope, Rope::from("abcd"));
    /// assert_eq!(an_rope, Rope::from("ab"));
    /// ```
    ///
    /// Inserting at an index in the middle inserts `rope` at that index:
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("ad");
    /// let new_rope = an_rope.insert_rope(1, &Rope::from("bc"));
    /// assert_eq!(new_rope, Rope::from("abcd"));
    /// assert_eq!(an_rope, Rope::from("ad"))
    /// ```
    #[inline]
    pub fn insert_rope<M>(&self, index: M, rope: &Rope) -> Rope
    where M: Metric
        , Self: Measured<M>
        , NodeLink: Measured<M>
        , String: Measured<M>
        , str: Measured<M>
        {
        if !rope.is_empty() {
            let len = self.measure();
            if index.into() == 0 {
                // if the rope is being inserted at index 0, just prepend it
                self.prepend(rope)
            } else if index == len {
                // if the rope is being inserted at index len, append it
                self.append(rope)
            } else {
                // split the rope at the given index
                let (left, right) = self.root.split(index);

                // construct the new root node with `Rope` inserted
                // rebalance the new rope
                Rope::from(&left + &rope.root + right)
            }
        } else {
            self.clone()
        }
    }

    /// Insert `s` into `index` in this `Rope`, returning a new `Rope`.
    ///
    /// # Returns
    /// * A new `Rope` with `s` inserted at `index`
    ///
    /// # Panics
    /// *  If `index` is greater than the length of this `Rope`
    ///
    /// # Time Complexity
    /// O(log _n_)
    ///
    /// # Examples
    ///
    /// Inserting at index 0 prepends `s` to this `Rope`:
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("cd");
    /// let an_rope = an_rope.insert_str(0, "ab");
    /// assert_eq!(an_rope, Rope::from("abcd"));
    /// ```
    ///
    /// Inserting at index `len` prepends `s` to this `Rope`:
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("ab");
    /// let new_rope = an_rope.insert_str(an_rope.len(), "cd");
    /// assert_eq!(new_rope, Rope::from("abcd"));
    /// assert_eq!(an_rope, Rope::from("ab"));
    /// ```
    ///
    /// Inserting at an index in the middle inserts `s` at that index:
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("ad");
    /// let new_rope = an_rope.insert_str(1, "bc");
    /// assert_eq!(an_rope, Rope::from("ad"));
    /// assert_eq!(new_rope, Rope::from("abcd"));
    /// ```
    #[inline]
    pub fn insert_str<M>(&self, index: M, s: &str) -> Rope
    where M: Metric
        , Self: Measured<M>
        , NodeLink: Measured<M>

        , String: Measured<M>
        , str: Measured<M>
        {
        assert!( index <= self.measure()
               , "Rope::insert_str: index {:?} was > length {:?}"
               , index, self.measure());
        self.insert_rope(index, &s.into())
    }

    /// Appends a `Rope` to the end of this `Rope`, returning a new `Rope`
    ///
    /// Note that this is equivalent to using the `+` operator.
    ///
    /// # Examples
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("abcd");
    /// let another_rope = an_rope.append(&Rope::from("efgh"));
    /// assert_eq!(&another_rope, "abcdefgh");
    /// assert_eq!(&an_rope, "abcd");
    /// ```
    pub fn append(&self, other: &Rope) -> Rope {
        if !other.is_empty() {
            Rope::from(&self.root + &other.root)
        } else {
            self.clone()
        }
    }

    /// Prepends a `Rope` to the end of this `Rope`, returning a new `Rope`
    ///
    /// # Examples
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("efgh");
    /// let another_rope = an_rope.prepend(&Rope::from("abcd"));
    /// assert_eq!(&an_rope, "efgh");
    /// assert_eq!(&another_rope, "abcdefgh");
    /// ```
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("");
    /// let another_rope = an_rope.prepend(&Rope::from("abcd"));
    /// assert_eq!(&an_rope, "");
    /// assert_eq!(&another_rope, "abcd");
    /// ```
    ///
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from("abcd");
    /// let another_rope = an_rope.prepend(&Rope::from(""));
    /// assert_eq!(&an_rope, "abcd");
    /// assert_eq!(&another_rope, &an_rope);
    /// assert_eq!(&another_rope, "abcd");
    /// ```
    pub fn prepend(&self, other: &Rope) -> Rope {
        if !other.is_empty() {
            Rope::from(&other.root + &self.root)
        } else {
            self.clone()
        }
    }



    /// Splits the rope into two ropes at the given index.
    ///
    /// # Examples
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from(String::from("abcd"));
    /// let (ab, cd) = an_rope.split(2);
    /// assert_eq!(ab, Rope::from(String::from("ab")));
    /// assert_eq!(cd, Rope::from(String::from("cd")));
    /// ```
    pub fn split<M: Metric>(&self, index: M) -> (Rope, Rope)
    where Self: Measured<M>
        , NodeLink: Measured<M>
        , String: Measured<M>
        , str: Measured<M>
        {
        assert!(index <= self.measure());
        let (l, r) = self.root.split(index);
        (Rope::from(l), Rope::from(r))
    }

    /// Rebalances this entire `Rope`, returning a balanced `Rope`.
    #[inline]
    #[cfg(any(test, feature = "rebalance"))]
    fn rebalance(&mut self) {
        if self.is_balanced() {
            // the rope is already balanced, do nothing
        } else {
            // rebalance the rope
            // self.root = self.root.rebalance();
        }
    }

    /// Returns true if this `Rope` is balanced.
    ///
    /// Balancing invariant:
    /// the rope length needs to be less than _F_(rope_length) where F is fibonacci
    #[inline]
    #[cfg(any(test, feature = "rebalance"))]
    fn is_balanced(&self) -> bool {
        self.root.is_balanced()
    }

    unstable_iters! {
        #[doc="Returns an iterator over all the strings in this `Rope`"]
        #[inline]
        pub fn strings<'a>(&'a self) -> impl Iterator<Item=&'a str> + 'a {
            self.root.strings()
        }

        #[doc="Returns an iterator over all the lines of text in this `Rope`."]
        pub fn lines<'a>(&'a self) -> impl Iterator<Item=RopeSlice<'a>> +'a  {
            {   // create a new block here so the macro will bind the `use` stmt
                use internals::IsLineEnding;
                let last_idx = self.len() - 1;
                Box::new(self.char_indices()
                             .filter_map(move |(i, c)|
                                if c.is_line_ending() { Some(i) }
                                // special case: slice to the end of the rope
                                // even if it doesn't end in a newline character
                                else if i == last_idx { Some(i + 1) }
                                else { None })
                              .scan(0, move |mut l, i|  {
                                    let last = *l;
                                    *l = i + 1;
                                    Some(self.slice(last..i))
                                }))
            }
        }
    }
    //
    //
    // /// Returns a move iterator over all the strings in this `Rope`
    // ///
    // /// Consumes `self`.
    // #[cfg(feature = "unstable")]
    // #[inline]
    // pub fn into_strings<'a>(self) -> impl Iterator<Item=String> + 'a {
    //     self.root.into_strings()
    // }
    //
    // /// Returns a move iterator over all the strings in this `Rope`
    // ///
    // /// Consumes `self`.
    // #[cfg(not(feature = "unstable"))]
    // #[inline]
    // pub fn into_strings<'a>(self) -> Box<Iterator<Item=String> + 'a> {
    //     self.root.into_strings()
    // }


    str_iters! {
        #[doc="Returns an iterator over all the bytes in this `Rope`.\n\
               \nAs a Rope consists of a sequence of bytes, we can iterate \
               through a rope by byte. This method returns such an iterator."]
        #[inline]
        impl bytes<u8> for Rope {}
        #[doc="Returns an iterator over all the characters in this `Rope`.\n\
               \nAs a `Rope` consists of valid UTF-8, we can iterate through a \
               `Rope` by `char`. This method returns such an iterator. \n\
               \nIt's important to remember that `char` represents a Unicode \
               Scalar Value, and may not match your idea of what a \
               'character' is. Iteration over grapheme clusters may be what \
               you actually want."]
        #[inline]
        impl chars<char> for Rope {}
        #[inline]
        impl char_indices<(usize, char)> for Rope {}
        #[inline]
        impl split_whitespace<&'a str> for Rope {}
        // #[inline]
        // impl lines<&'a str> for Rope {}
    }

    unicode_seg_iters! {
        #[doc=
            "Returns an iterator over the [grapheme clusters][graphemes] of \
             `self`.\n\

             [graphemes]: \
             http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries\
             \n\
             The iterator is over the  *extended grapheme clusters*; as \
             [UAX#29]\
             (http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)\
             recommends extended grapheme cluster boundaries for general \
             processing."]
        #[inline]
        impl graphemes<&'a str> for Rope {}
        #[doc=
            "Returns an iterator over the words of `self`, separated on \
            [UAX#29 word boundaries]\
            (http://www.unicode.org/reports/tr29/#Word_Boundaries).\n\n\

            Here, \"words\" are just those substrings which, after splitting on\
            UAX#29 word boundaries, contain any alphanumeric characters. That \
            is, the substring must contain at least one character with the \
            [Alphabetic](http://unicode.org/reports/tr44/#Alphabetic) \
            property, or with [General_Category=Number]\
            (http://unicode.org/reports/tr44/#General_Category_Values)."]
        #[inline]
        impl unicode_words<&'a str> for Rope {}
        #[doc=
            "Returns an iterator over substrings of `self` separated on \
            [UAX#29 word boundaries]\
            (http://www.unicode.org/reports/tr29/#Word_Boundaries). \n\n\
            The concatenation of the substrings returned by this function is \
            just the original string."]
        #[inline]
        impl split_word_bounds<&'a str> for Rope {}
        // #[inline]
        // impl grapheme_indices<(usize, &'a str)> for Rope {}
        // #[inline]
        // impl split_word_bound_indices<(usize, &'a str)> for Rope {}
    }

    /// Returns an iterator over the grapheme clusters of `self` and their
    /// byte offsets. See `graphemes()` for more information.
    ///
    /// # Examples
    ///
    /// ```
    /// # use an_rope::Rope;
    /// let rope = Rope::from("a̐éö̲\r\n");
    /// let gr_inds = rope.grapheme_indices()
    ///                   .collect::<Vec<(usize, &str)>>();
    /// let b: &[_] = &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
    ///
    /// assert_eq!(&gr_inds[..], b);
    /// ```
    #[inline]
    pub fn grapheme_indices(&self) -> internals::GraphemeIndices {
        self.root.grapheme_indices()
    }

    /// Returns an iterator over substrings of `self`, split on UAX#29 word
    /// boundaries, and their offsets. See `split_word_bounds()` for more
    /// information.
    ///
    /// # Example
    ///
    /// ```
    /// # use an_rope::Rope;
    /// let rope = Rope::from("Brr, it's 29.3°F!");
    /// let swi1 = rope.split_word_bound_indices()
    ///                .collect::<Vec<(usize, &str)>>();
    /// let b: &[_] = &[ (0, "Brr"), (3, ","), (4, " "), (5, "it's")
    ///                , (9, " "), (10, "29.3"),  (14, "°"), (16, "F")
    ///                , (17, "!")];
    ///
    /// assert_eq!(&swi1[..], b);
    /// ```
    #[inline]
    pub fn split_word_bound_indices(&self) -> internals::UWordBoundIndices {
        self.root.split_word_bound_indices()
    }

    /// Returns true if the bytes in `self` equal the bytes in `other`
    #[inline]
    fn bytes_eq<I>(&self, other: I) -> bool
    where I: Iterator<Item=u8> {
        self.bytes().zip(other).all(|(a, b)| a == b)
    }

    /// Returns an immutable slice of this `Rope` between the given indices.
    ///
    /// # Arguments
    /// + `range`: A [`RangeArgument`](https://doc.rust-lang.org/nightly/collections/range/trait.RangeArgument.html)
    /// specifying the range to slice. This can be produced by range syntax
    /// like `..`, `a..`, `..b` or `c..d`.
    ///
    /// # Panics
    /// If the start or end indices of the range to slice exceed the length of
    /// this `Rope`.
    ///
    /// # Examples
    /// ```ignore
    //  this doctest fails to link on my macbook for Secret Reasons.
    //  i'd really like to know why...
    //      - eliza, 12/23/2016
    /// #![feature(collections)]
    /// #![feature(collections_range)]
    ///
    /// extern crate collections;
    /// extern crate an_rope;
    /// # fn main() {
    /// use collections::range::RangeArgument;
    /// use an_rope::Rope;
    ///
    /// let rope = Rope::from("this is an example string");
    /// assert_eq!(&rope.slice(4..6), "is");
    /// # }
    /// ```
    #[inline]
    #[cfg(feature = "unstable")]
    pub fn slice<R>(&self, range: R) -> RopeSlice
    where R: RangeArgument<usize> {
        RopeSlice::new(&self.root, range)
    }
    #[cfg(not(feature = "unstable"))]
    pub fn slice(&self, range: ops::Range<usize>) -> RopeSlice {
        RopeSlice::new(&self.root, range)
    }

}

impl convert::Into<Vec<u8>> for Rope {
    fn into(self) -> Vec<u8> {
        unimplemented!()
    }

}

//-- comparisons ----------------------------------------------------
impl cmp::Eq for Rope {}
impl cmp::PartialEq for Rope {
    /// A rope equals another rope if all the bytes in both are equal.
    ///
    /// # Examples
    /// ```
    /// use an_rope::Rope;
    /// assert!(Rope::from("abcd") == Rope::from("abcd"));
    /// ```
    /// ```
    /// use an_rope::Rope;
    /// assert!(Rope::from("abcd") != Rope::from("ab"));
    /// ```
    /// ```
    /// use an_rope::Rope;
    /// assert!(Rope::from("abcd") != Rope::from("dcab"))
    /// ```
    #[inline]
    fn eq(&self, other: &Rope) -> bool {
        if self.len() == other.len() {
            self.bytes_eq(other.bytes())
        } else {
            false
        }
    }
}

impl cmp::PartialEq<str> for Rope {
    /// A rope equals a string if all the bytes in the string equal the rope's.
    ///
    /// # Examples
    /// ```
    /// use an_rope::Rope;
    /// assert!(&Rope::from("abcd") == "abcd");
    /// ```
    /// ```
    /// use an_rope::Rope;
    /// assert!(&Rope::from("abcd") != "ab");
    /// ```
    /// ```
    /// use an_rope::Rope;
    /// assert!(&Rope::from("abcd") != "dcab");
    /// ```
    #[inline]
    fn eq(&self, other: &str) -> bool {
        if self.len() == other.len() {
            self.bytes_eq(other.bytes())
        } else {
            false
        }
    }
}


impl cmp::PartialEq<String> for Rope {
    /// A rope equals a string if all the bytes in the string equal the rope's.
    ///
    /// # Examples
    /// ```
    /// use an_rope::Rope;
    /// assert!(Rope::from("abcd") == String::from("abcd"));
    /// ```
    /// ```
    /// use an_rope::Rope;
    /// assert!(Rope::from("abcd") != String::from("ab"));
    /// ```
    /// ```
    /// use an_rope::Rope;
    /// assert!(Rope::from("abcd") != String::from("dcab"));
    /// ```
    #[inline]
    fn eq(&self, other: &String) -> bool {
        if self.len() == other.len() {
            self.bytes_eq(other.bytes())
        } else {
            false
        }
    }
}


//-- concatenation --------------------------------------------------
impl<'a> ops::Add for &'a Rope {
    type Output = Rope;
    /// Non-destructively concatenate two `Rope`s, returning a new `Rope`.
    ///
    /// # Examples
    /// ```
    /// use an_rope::Rope;
    /// let rope = Rope::from(String::from("ab"));
    /// assert_eq!( &rope + &Rope::from(String::from("cd"))
    ///           , Rope::from(String::from("abcd")) );
    /// ```
    #[inline] fn add(self, other: Self) -> Rope { self.append(other) }

}

impl ops::Add for Rope {
    type Output = Rope;
    /// Non-destructively concatenate two `Rope`s, returning a new `Rope`.
    ///
    /// # Examples
    /// ```
    /// use an_rope::Rope;
    /// let rope = Rope::from(String::from("ab"));
    /// assert_eq!( rope + Rope::from(String::from("cd"))
    ///           , Rope::from(String::from("abcd")) );
    /// ```
    #[inline] fn add(self, other: Self) -> Rope { self.append(&other) }
}

impl ops::Add<String> for Rope {
    type Output = Rope;
    /// Non-destructively concatenate a `Rope` and a `String`.
    ///
    /// Returns a new `Rope`
    ///
    /// # Examples
    /// ```
    /// use an_rope::Rope;
    /// let rope = Rope::from(String::from("ab"));
    /// assert_eq!( rope + String::from("cd")
    ///           , Rope::from(String::from("abcd")));
    /// ```
    #[inline] fn add(self, other: String) -> Rope {
         self.append(&Rope::from(other))
    }
}


impl<'a, 'b> ops::Add<&'b str> for &'a Rope {
    type Output = Rope;
    /// Non-destructively concatenate a `Rope` and an `&str`.
    ///
    /// Returns a new `Rope`
    ///
    /// # Examples
    /// ```
    /// use an_rope::Rope;
    /// let rope = Rope::from(String::from("ab"));
    /// assert_eq!( &rope + "cd"
    ///           , Rope::from(String::from("abcd")));
    /// ```
    #[inline] fn add(self, other: &'b str) -> Rope {
         self.append(&Rope::from(other.to_owned()))
     }

}

impl<'a> ops::Add<&'a str> for Rope {
    type Output = Rope;
    /// Non-destructively concatenate a `Rope` and an `&str`.
    ///
    /// Returns a new `Rope`
    ///
    /// # Examples
    /// ```
    /// use an_rope::Rope;
    /// let rope = Rope::from(String::from("ab"));
    /// assert_eq!( rope + "cd"
    ///           , Rope::from(String::from("abcd")));
    /// ```
    #[inline] fn add(self, other: &'a str) -> Rope {
         self.append(&Rope::from(other.to_owned()))
     }

}

impl ops::Index<usize> for Rope {
    type Output = str;

    /// Recursively index the Rope to return the `i` th character.
    ///
    /// # Examples
    /// ```
    /// use an_rope::Rope;
    /// let an_rope = Rope::from(String::from("abcd"));
    /// assert_eq!(&an_rope[0], "a");
    /// assert_eq!(&an_rope[1], "b");
    /// assert_eq!(&an_rope[2], "c");
    /// assert_eq!(&an_rope[3], "d");
    /// ```
    ///
    /// # Time complexity
    /// _O_(log _n_)
    ///
    #[inline]
    fn index(&self, i: usize) -> &str {
        &self.root[i]
    }
}

//-- slicing operators ----------------------------------------------
impl ops::Index<ops::Range<usize>> for Rope {
    type Output = str;

    // Index a substring
    fn index(&self, _i: ops::Range<usize>) -> &str {
        unimplemented!()
    }
}

impl ops::Index<ops::RangeTo<usize>> for Rope {
    type Output = str;

    fn index(&self, _i: ops::RangeTo<usize>) -> &str {
        unimplemented!()
    }
}

impl ops::Index<ops::RangeFrom<usize>> for Rope {
    type Output = str;

    fn index(&self, _i: ops::RangeFrom<usize>) -> &str {
        unimplemented!()
    }
}

impl ops::IndexMut<ops::Range<usize>> for Rope {
    fn index_mut(&mut self, _i: ops::Range<usize>) -> &mut str {
        unimplemented!()
    }
}

impl ops::IndexMut<ops::RangeTo<usize>> for Rope {
    fn index_mut(&mut self, _i: ops::RangeTo<usize>) -> &mut str {
        unimplemented!()
    }
}

impl ops::IndexMut<ops::RangeFrom<usize>> for Rope {
    fn index_mut(&mut self, _i: ops::RangeFrom<usize>) -> &mut str {
        unimplemented!()
    }
}

// impl<'a> Borrow<RopeSlice<'a>> for &'a Rope {
//     fn borrow(&self) -> &RopeSlice<'a> {
//         unimplemented!()
//     }
// }

// impl<A> iter::Extend<A> for Rope
// where Rope: iter::FromIterator<A>{
//
//     fn extend<B>(&mut self, iter: B)
//     where B: IntoIterator<Item=A> {
//
//         self.append(&(iter.into_iter().collect()));
//
//     }
//
// }

impl iter::FromIterator<char> for Rope {

    fn from_iter<I>(iter: I) -> Rope
    where I: IntoIterator<Item=char> {
        let s: String = iter.into_iter().collect();
        Rope::from(s)

    }

}

impl iter::FromIterator<String> for Rope {

    fn from_iter<I>(iter: I) -> Rope
    where I: IntoIterator<Item=String> {
        iter.into_iter().fold(Rope::new(), |acc, x| acc + x)
    }

}

impl iter::FromIterator<Rope> for Rope {

    fn from_iter<I>(iter: I) -> Rope
    where I: IntoIterator<Item=Rope> {
        iter.into_iter().fold(Rope::new(), |acc, x| acc + x)
    }

}

impl<'a> iter::FromIterator<&'a char> for Rope {

    fn from_iter<I>(iter: I) -> Rope
    where I: IntoIterator<Item=&'a char> {
        let s: String = iter.into_iter().fold(String::new(), |mut acc, x| {acc.push(*x); acc});
        Rope::from(s)
    }

}

impl<'a> iter::FromIterator<&'a str> for Rope {

    fn from_iter<I>(iter: I) -> Rope
    where I: IntoIterator<Item=&'a str> {
        iter.into_iter().fold(Rope::new(), |acc, x| acc + x)
    }

}