an_rope/lib.rs
1//! # An rope.
2//!
3//! An immutable Rope data structure for storing large text documents. This
4//! implementation is a component of the [`an-editor`]
5//! project.
6//!
7//! A rope is an efficient data structure for large strings. It's
8//! essentially a binary tree whose leaves are strings.
9//!
10//! For more information, see the following resources:
11//!
12//! + http://scienceblogs.com/goodmath/2009/01/26/ropes-twining-together-strings/
13//! + https://www.ibm.com/developerworks/library/j-ropes/
14//! + http://citeseer.ist.psu.edu/viewdoc/download?doi=10.1.1.14.9450&rep=rep1&type=pdf
15//! [`an-editor`]: https://github.com/an-cabal/an-editor
16
17#![cfg_attr( feature = "unstable"
18 , feature( const_fn
19 , box_syntax, box_patterns
20 , conservative_impl_trait
21 , collections, collections_range
22 , inclusive_range_syntax
23 ))]
24#![cfg_attr( all( test, feature = "unstable")
25 , feature( test, insert_str) )]
26#![cfg_attr( feature = "clippy", feature(plugin) )]
27#![cfg_attr( feature = "clippy", plugin(clippy) )]
28#![cfg_attr( feature = "clippy", allow(unused_variables, dead_code))]
29
30#[macro_use] extern crate macro_attr;
31#[macro_use] extern crate newtype_derive;
32
33#[cfg(feature = "unstable")] extern crate collections;
34#[cfg(feature = "unstable")] use collections::range::RangeArgument;
35
36extern crate unicode_segmentation;
37
38use std::cmp;
39use std::ops;
40use std::convert;
41use std::fmt;
42use std::string;
43use std::iter;
44
45macro_rules! or_zero {
46 ($a: expr, $b: expr) => { if $a > $b { $a - $b } else { 0 } }
47}
48
49#[cfg(feature = "tendril")] extern crate tendril;
50
51#[cfg(test)] #[macro_use] extern crate quickcheck;
52#[cfg(test)] mod test;
53#[cfg(all( test, feature = "unstable"))] mod bench;
54
55mod unicode;
56pub mod metric;
57
58use metric::{Measured, Metric};
59use self::internals::{Node, NodeLink};
60
61pub use self::slice::{ RopeSlice
62 //, RopeSliceMut
63 };
64
65impl<T> convert::From<T> for Rope
66where T: convert::Into<NodeLink> {
67 #[inline] fn from(that: T) -> Self {
68 Rope { root: that.into().rebalance() }
69 }
70}
71
72/// A Rope
73///
74/// This Rope implementation aims to eventually function as a superset of
75/// [`String`](https://doc.rust-lang.org/1.3.0/std/string/struct.String.html),
76/// providing the same API plus additional methods. Therefore, code which uses
77/// `String` can easily be ported to use `Rope`.
78///
79/// `Rope` provides two APIs for editing a `Rope`: a destructive,
80/// append-in-place API whose methods match those of `String`, and a
81/// non-destructive, persistant API. The persistant API's methods have names
82/// prefixed with ``, such as `push()` and `append()`.
83///
84#[derive(Clone, Default)]
85pub struct Rope {
86 // can we get away with having these be of &str or will they need
87 // to be string?
88 root: NodeLink
89}
90
91pub trait Split: Sized {
92 fn split<M>(&self, index: M) -> (Self,Self)
93 where M: Metric
94 , Self: Measured<M>;
95}
96
97impl<M> Measured<M> for Rope
98where M: Metric
99 , NodeLink: Measured<M>
100 , String: Measured<M>
101 {
102
103 #[inline] fn to_byte_index(&self, index: M) -> Option<usize> {
104 self.root.to_byte_index(index)
105 }
106
107 #[inline] fn measure(&self) -> M { self.root.measure() }
108
109 #[inline] fn measure_weight(&self) -> M { self.root.measure_weight() }
110
111}
112
113impl fmt::Debug for Rope {
114 #[inline]
115 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
116 write!(f, "Rope[\"{}\"] {:?}", self.root, self.root)
117 }
118}
119
120impl fmt::Display for Rope {
121
122 #[inline]
123 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
124 write!(f, "{}", self.root)
125 }
126}
127 #[cfg(feature = "unstable")]
128macro_rules! unstable_iters {
129 ( $($(#[$attr:meta])*
130 pub fn $name:ident$(<$lf:tt>)*(&'a $sel:ident) -> $ty:ty {
131 $body:expr
132 })+ ) => { $(
133 $(#[$attr])*
134 #[cfg_attr(feature = "clippy", allow(needless_lifetimes))]
135 pub fn $name$(<$lf>)*(&'a $sel) -> $ty {
136 $body
137 }
138 )+ };
139 ( $($(#[$attr:meta])*
140 pub fn $name:ident$(<$lf:tt>)*(&'a mut $sel:ident) -> $ty:ty {
141 $body:expr
142 })+ ) => { $(
143 $(#[$attr])*
144 #[cfg(feature = "unstable")]
145 #[cfg_attr(feature = "clippy", allow(needless_lifetimes))]
146 pub fn $name$(<$lf>)*(&'a mut $sel) -> $ty {
147 $body
148 }
149 )+ };
150}
151
152#[cfg(not(feature = "unstable"))]
153macro_rules! unstable_iters {
154 ( $($(#[$attr:meta])*
155 pub fn $name:ident$(<$lf:tt>)*(&'a $sel:ident) -> impl Iterator<Item=$ty:ty> + 'a {
156 $body:expr
157 })+ ) => ($(
158 $(#[$attr])*
159 #[cfg(not(feature = "unstable"))]
160 #[cfg_attr(feature = "clippy", allow(needless_lifetimes))]
161 pub fn $name$(<$lf>)*(&'a $sel) -> Box<Iterator<Item=$ty> + 'a> {
162 Box::new($body)
163 }
164 )+);
165 ( $( $(#[$attr:meta])*
166 pub fn $name:ident$(<$lf:tt>)*(&'a mut $sel:ident) - impl Iterator<Item=$ty:ty> + 'a {
167 $body:expr
168 })+ ) => { $({
169 $(#[$attr])*
170 #[cfg(not(feature = "unstable"))]
171 #[cfg_attr(feature = "clippy", allow(needless_lifetimes))]
172 pub fn $name$(<$lf>)*(&'a mut $sel) -> Box<Iterator<Item=$ty> + 'a> {
173 Box::new($body)
174 }
175 })+
176 };
177}
178macro_rules! str_iters {
179 ( $($(#[$attr:meta])* impl $name: ident<$ty: ty> for Node {})+ ) => { $(
180 unstable_iters! {
181 $(#[$attr])*
182 pub fn $name<'a>(&'a self) -> impl Iterator<Item=$ty> + 'a{
183 self.strings().flat_map(str::$name)
184 }
185 }
186 )+ };
187
188 ( $($(#[$attr:meta])* impl $name: ident<$ty: ty> for Rope {})+ )=> { $(
189 unstable_iters! {
190 $(#[$attr])*
191 pub fn $name<'a>(&'a self) -> impl Iterator<Item=$ty> + 'a{
192 self.root.$name()
193 }
194 }
195 )+ }
196
197}
198
199
200macro_rules! unicode_seg_iters {
201 ( $($(#[$attr:meta])* impl $name: ident for Node { extend })+ ) => { $(
202
203 unstable_iters! {
204 $(#[$attr])*
205 pub fn $name<'a>(&'a self) -> impl Iterator<Item=&'a str> + 'a {
206 { // this block is required so that the macro will bind the
207 // `use` statement
208 use unicode_segmentation::UnicodeSegmentation;
209 self.strings()
210 .flat_map(|s| UnicodeSegmentation::$name(s, true))
211 }
212 }
213 }
214 )+ };
215 ( $($(#[$attr:meta])* impl $name: ident for Node {} )+ ) => { $(
216 unstable_iters!{
217 $(#[$attr])*
218 pub fn $name<'a>(&'a self) -> impl Iterator<Item=&'a str> + 'a {
219 { // this block is required so that the macro will bind the
220 // `use` statement
221 use unicode_segmentation::UnicodeSegmentation;
222 self.strings().flat_map(UnicodeSegmentation::$name)
223 }
224 }
225 }
226 )+ };
227 ( $($(#[$attr:meta])* impl $name: ident<$ty: ty> for Rope {})+ )=> { $(
228 unstable_iters! {
229 $(#[$attr])*
230 pub fn $name<'a>(&'a self) -> impl Iterator<Item=$ty> + 'a {
231 self.root.$name()
232 }
233 }
234 )+ }
235
236}
237
238mod internals;
239mod slice;
240
241impl Rope {
242
243 /// Converts a vector of bytes to a `Rope`.
244 ///
245 /// If you are sure that the byte slice is valid UTF-8, and you don't want
246 /// to incur the overhead of the validity check, there is an unsafe version
247 /// of this function, `from_utf8_unchecked(),`` which has the same behavior
248 /// but skips the check.
249 ///
250 /// This method will take care to not copy the vector, for efficiency's
251 /// sake.
252 ///
253 /// # Errors
254 ///
255 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
256 /// provided bytes are not UTF-8. The vector you moved in is also included.
257 ///
258 /// # Examples
259 ///
260 /// Basic usage:
261 ///
262 /// ```
263 /// use an_rope::Rope;
264 ///
265 /// // some bytes, in a vector
266 /// let sparkle_heart = vec![240, 159, 146, 150];
267 ///
268 /// // We know these bytes are valid, so we'll use `unwrap()`.
269 /// let sparkle_heart = Rope::from_utf8(sparkle_heart).unwrap();
270 ///
271 /// assert_eq!(&sparkle_heart, "💖");
272 /// ```
273 ///
274 /// Incorrect bytes:
275 ///
276 /// ```
277 /// use an_rope::Rope;
278 ///
279 /// // some invalid bytes, in a vector
280 /// let sparkle_heart = vec![0, 159, 146, 150];
281 ///
282 /// assert!(Rope::from_utf8(sparkle_heart).is_err());
283 /// ```
284 ///
285 #[inline]
286 pub fn from_utf8(vec: Vec<u8>) -> Result<Rope, string::FromUtf8Error> {
287 String::from_utf8(vec).map(Rope::from)
288 }
289
290 /// Decode a UTF-16 encoded vector `v` into a `Rope`,
291 /// returning `Err` if `v` contains any invalid data.
292 #[inline]
293 pub fn from_utf16(v: &[u16]) -> Result<Rope, string::FromUtf16Error> {
294 String::from_utf16(v).map(Rope::from)
295 }
296
297 /// Converts a vector of bytes to a `Rope` without checking that the
298 /// vector contains valid UTF-8.
299 ///
300 /// See the safe version, [`from_utf8()`], for more details.
301 ///
302 /// [`from_utf8()`]: struct.Rope.html#method.from_utf8
303 ///
304 /// # Safety
305 ///
306 /// This function is unsafe because it does not check that the bytes passed
307 /// to it are valid UTF-8. If this constraint is violated, it may cause
308 /// memory unsafety issues with future users of the `Rope`, as the rest of
309 /// the standard library assumes that `Rope`s are valid UTF-8.
310 ///
311 /// # Examples
312 ///
313 /// Basic usage:
314 ///
315 /// ```
316 /// use an_rope::Rope;
317 ///
318 /// // some bytes, in a vector
319 /// let sparkle_heart = vec![240, 159, 146, 150];
320 ///
321 /// let sparkle_heart = unsafe {
322 /// Rope::from_utf8_unchecked(sparkle_heart)
323 /// };
324 ///
325 /// assert_eq!(&sparkle_heart, "💖");
326 /// ```
327 #[inline]
328 pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> Rope {
329 Rope::from(String::from_utf8_unchecked(bytes))
330 }
331
332 /// Returns a new empty Rope
333 ///
334 /// # Examples
335 /// ```
336 /// use an_rope::Rope;
337 /// let mut an_rope = Rope::new();
338 /// assert_eq!(an_rope.len(), 0);
339 /// ```
340 #[inline] pub fn new() -> Rope { Rope::from(Node::empty()) }
341
342 /// Returns the length of this Rope
343 ///
344 /// # Examples
345 ///
346 /// An empty `Rope` should have length 0.
347 ///
348 /// ```
349 /// use an_rope::Rope;
350 /// let mut an_empty_rope = Rope::new();
351 /// assert_eq!(an_empty_rope.len(), 0);
352 /// ```
353 ///
354 /// ```
355 /// use an_rope::Rope;
356 /// let mut an_empty_rope = Rope::from(String::from(""));
357 /// assert_eq!(an_empty_rope.len(), 0);
358 /// ```
359 ///
360 /// A `Rope` with text should have length equal to the number of
361 /// characters in the `Rope`.
362 ///
363 /// ```
364 /// use an_rope::Rope;
365 /// let mut an_rope = Rope::from(String::from("a string"));
366 /// assert_eq!(an_rope.len(), "a string".len());
367 /// ```
368 pub fn len(&self) -> usize { self.root.len() }
369
370 /// Returns `true` if this `Rope` is empty.
371 ///
372 /// # Examples
373 ///
374 /// A `Rope` with no characters should be empty:
375 ///
376 /// ```
377 /// use an_rope::Rope;
378 /// let an_empty_rope = Rope::new();
379 /// assert!(an_empty_rope.is_empty());
380 /// ```
381 ///
382 /// ```
383 /// use an_rope::Rope;
384 /// let an_empty_rope = Rope::from(String::from(""));
385 /// assert!(an_empty_rope.is_empty());
386 /// ```
387 ///
388 /// A `Rope` with characters should not be empty:
389 ///
390 /// ```
391 /// use an_rope::Rope;
392 /// let an_rope = Rope::from("a string");
393 /// assert!(!an_rope.is_empty());
394 /// ```
395 #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 }
396
397 /// Insert `ch` into `index` in this `Rope`, returning a new `Rope`.
398 ///
399 ///
400 /// # Returns
401 /// * A new `Rope` with `ch` inserted at `index`
402 ///
403 /// # Time Complexity
404 /// O(log _n_)
405 ///
406 /// # Panics
407 /// * If `index` is greater than the length of this `Rope`
408 ///
409 /// # Examples
410 ///
411 /// Inserting at index 0 prepends `rope` to this `Rope`:
412 ///
413 /// ```
414 /// use an_rope::Rope;
415 /// let an_rope = Rope::from("bcd");
416 /// let new_rope = an_rope.insert(0, 'a');
417 /// assert_eq!(new_rope, Rope::from("abcd"));
418 /// assert_eq!(an_rope, Rope::from("bcd"));
419 /// ```
420 ///
421 /// Inserting at index `len` prepends `char` to this `Rope`:
422 ///
423 /// ```
424 /// use an_rope::Rope;
425 /// let an_rope = Rope::from("abc");
426 /// let new_rope = an_rope.insert(an_rope.len(), 'd');
427 /// assert_eq!(new_rope, Rope::from("abcd"));
428 /// assert_eq!(an_rope, Rope::from("abc"));
429 /// ```
430 ///
431 /// Inserting at an index in the middle inserts `char` at that index:
432 ///
433 /// ```
434 /// use an_rope::Rope;
435 /// let an_rope = Rope::from("acd");
436 /// let new_rope = an_rope.insert(1, 'b');
437 /// assert_eq!(new_rope, Rope::from("abcd"));
438 /// assert_eq!(an_rope, Rope::from("acd"));
439 /// ```
440 #[inline]
441 #[inline]
442 pub fn insert<M>(&self, index: M, ch: char) -> Rope
443 where M: Metric
444 , Self: Measured<M>
445 , NodeLink: Measured<M>
446 , String: Measured<M>
447 , str: Measured<M>
448 {
449 assert!( index <= self.measure()
450 , "Rope::insert: index {:?} was > length {:?}"
451 , index, self.measure());
452 // TODO: this is gross...
453 let mut s = String::new();
454 s.push(ch);
455 self.insert_rope(index, &Rope::from(s))
456 }
457
458
459
460 /// Delete the range `range` from this `Rope`,
461 ///
462 /// # Panics
463 /// * If the start or end of `range` are indices outside of the `Rope`
464 /// * If the end index of `range` is greater than the start index
465 ///
466 /// # Time Complexity
467 /// O(log _n_)
468 ///
469 /// # Examples
470 ///
471 /// Deleting "not" from this `Rope`:
472 ///
473 /// ```
474 /// use an_rope::Rope;
475 /// let an_rope = Rope::from("this is not fine".to_string());
476 /// let an_rope = an_rope.delete((8..12));
477 /// assert_eq!(&an_rope, "this is fine");
478 /// ```
479 #[inline]
480 #[cfg(feature = "unstable")]
481 pub fn delete<R, M>(&self, range: R) -> Rope
482 where R: RangeArgument<M>
483 , M: Metric
484 , Rope: Measured<M>
485 , NodeLink: Measured<M>
486 , String: Measured<M>
487 , str: Measured<M>
488 {
489 let start = range.start().map(|s| *s)
490 .unwrap_or_else(|| { M::default() });
491 let end = range.end().map(|e| *e)
492 .unwrap_or_else(|| { self.measure() });
493
494 assert!( start <= end
495 , "invalid index! start {:?} > end {:?}", end, start);
496 let (l, r) = self.root.split(start);
497 let (_, r) = r.split(end - start);
498 Rope::from(Node::new_branch(l, r))
499 }
500
501 #[inline]
502 #[cfg(not(feature = "unstable"))]
503 pub fn delete<M: Metric>(&self, range: ops::Range<M>) -> Rope
504 where NodeLink: Measured<M>
505 , String: Measured<M>
506 , str: Measured<M>
507 {
508 let (l, r) = self.root.split(range.start);
509 let (_, r) = r.split(range.end - range.start);
510 Rope::from(Node::new_branch(l, r))
511 }
512
513
514 /// Insert `rope` into `index` in this `Rope`, returning a new `Rope`.
515 ///
516 /// # Returns
517 /// * A new `Rope` with `rope` inserted at `index`
518 ///
519 /// # Time Complexity
520 /// O(log _n_)
521 ///
522 /// # Panics
523 /// * If `index` is greater than the length of this `Rope`
524 ///
525 /// # Examples
526 ///
527 /// Inserting at index 0 prepends `rope` to this `Rope`:
528 ///
529 /// ```
530 /// use an_rope::Rope;
531 /// let an_rope = Rope::from("cd");
532 /// let new_rope = an_rope.insert_rope(0, &Rope::from("ab"));
533 /// assert_eq!(new_rope, Rope::from("abcd"));
534 /// assert_eq!(an_rope, Rope::from("cd"));
535 /// ```
536 ///
537 /// Inserting at index `len` prepends `rope` to this `Rope`:
538 ///
539 /// ```
540 /// use an_rope::Rope;
541 /// let an_rope = Rope::from("ab");
542 /// let new_rope = an_rope.insert_rope(an_rope.len(), &Rope::from("cd"));
543 /// assert_eq!(new_rope, Rope::from("abcd"));
544 /// assert_eq!(an_rope, Rope::from("ab"));
545 /// ```
546 ///
547 /// Inserting at an index in the middle inserts `rope` at that index:
548 ///
549 /// ```
550 /// use an_rope::Rope;
551 /// let an_rope = Rope::from("ad");
552 /// let new_rope = an_rope.insert_rope(1, &Rope::from("bc"));
553 /// assert_eq!(new_rope, Rope::from("abcd"));
554 /// assert_eq!(an_rope, Rope::from("ad"))
555 /// ```
556 #[inline]
557 pub fn insert_rope<M>(&self, index: M, rope: &Rope) -> Rope
558 where M: Metric
559 , Self: Measured<M>
560 , NodeLink: Measured<M>
561 , String: Measured<M>
562 , str: Measured<M>
563 {
564 if !rope.is_empty() {
565 let len = self.measure();
566 if index.into() == 0 {
567 // if the rope is being inserted at index 0, just prepend it
568 self.prepend(rope)
569 } else if index == len {
570 // if the rope is being inserted at index len, append it
571 self.append(rope)
572 } else {
573 // split the rope at the given index
574 let (left, right) = self.root.split(index);
575
576 // construct the new root node with `Rope` inserted
577 // rebalance the new rope
578 Rope::from(&left + &rope.root + right)
579 }
580 } else {
581 self.clone()
582 }
583 }
584
585 /// Insert `s` into `index` in this `Rope`, returning a new `Rope`.
586 ///
587 /// # Returns
588 /// * A new `Rope` with `s` inserted at `index`
589 ///
590 /// # Panics
591 /// * If `index` is greater than the length of this `Rope`
592 ///
593 /// # Time Complexity
594 /// O(log _n_)
595 ///
596 /// # Examples
597 ///
598 /// Inserting at index 0 prepends `s` to this `Rope`:
599 ///
600 /// ```
601 /// use an_rope::Rope;
602 /// let an_rope = Rope::from("cd");
603 /// let an_rope = an_rope.insert_str(0, "ab");
604 /// assert_eq!(an_rope, Rope::from("abcd"));
605 /// ```
606 ///
607 /// Inserting at index `len` prepends `s` to this `Rope`:
608 ///
609 /// ```
610 /// use an_rope::Rope;
611 /// let an_rope = Rope::from("ab");
612 /// let new_rope = an_rope.insert_str(an_rope.len(), "cd");
613 /// assert_eq!(new_rope, Rope::from("abcd"));
614 /// assert_eq!(an_rope, Rope::from("ab"));
615 /// ```
616 ///
617 /// Inserting at an index in the middle inserts `s` at that index:
618 ///
619 /// ```
620 /// use an_rope::Rope;
621 /// let an_rope = Rope::from("ad");
622 /// let new_rope = an_rope.insert_str(1, "bc");
623 /// assert_eq!(an_rope, Rope::from("ad"));
624 /// assert_eq!(new_rope, Rope::from("abcd"));
625 /// ```
626 #[inline]
627 pub fn insert_str<M>(&self, index: M, s: &str) -> Rope
628 where M: Metric
629 , Self: Measured<M>
630 , NodeLink: Measured<M>
631
632 , String: Measured<M>
633 , str: Measured<M>
634 {
635 assert!( index <= self.measure()
636 , "Rope::insert_str: index {:?} was > length {:?}"
637 , index, self.measure());
638 self.insert_rope(index, &s.into())
639 }
640
641 /// Appends a `Rope` to the end of this `Rope`, returning a new `Rope`
642 ///
643 /// Note that this is equivalent to using the `+` operator.
644 ///
645 /// # Examples
646 ///
647 /// ```
648 /// use an_rope::Rope;
649 /// let an_rope = Rope::from("abcd");
650 /// let another_rope = an_rope.append(&Rope::from("efgh"));
651 /// assert_eq!(&another_rope, "abcdefgh");
652 /// assert_eq!(&an_rope, "abcd");
653 /// ```
654 pub fn append(&self, other: &Rope) -> Rope {
655 if !other.is_empty() {
656 Rope::from(&self.root + &other.root)
657 } else {
658 self.clone()
659 }
660 }
661
662 /// Prepends a `Rope` to the end of this `Rope`, returning a new `Rope`
663 ///
664 /// # Examples
665 ///
666 /// ```
667 /// use an_rope::Rope;
668 /// let an_rope = Rope::from("efgh");
669 /// let another_rope = an_rope.prepend(&Rope::from("abcd"));
670 /// assert_eq!(&an_rope, "efgh");
671 /// assert_eq!(&another_rope, "abcdefgh");
672 /// ```
673 ///
674 /// ```
675 /// use an_rope::Rope;
676 /// let an_rope = Rope::from("");
677 /// let another_rope = an_rope.prepend(&Rope::from("abcd"));
678 /// assert_eq!(&an_rope, "");
679 /// assert_eq!(&another_rope, "abcd");
680 /// ```
681 ///
682 /// ```
683 /// use an_rope::Rope;
684 /// let an_rope = Rope::from("abcd");
685 /// let another_rope = an_rope.prepend(&Rope::from(""));
686 /// assert_eq!(&an_rope, "abcd");
687 /// assert_eq!(&another_rope, &an_rope);
688 /// assert_eq!(&another_rope, "abcd");
689 /// ```
690 pub fn prepend(&self, other: &Rope) -> Rope {
691 if !other.is_empty() {
692 Rope::from(&other.root + &self.root)
693 } else {
694 self.clone()
695 }
696 }
697
698
699
700 /// Splits the rope into two ropes at the given index.
701 ///
702 /// # Examples
703 /// ```
704 /// use an_rope::Rope;
705 /// let an_rope = Rope::from(String::from("abcd"));
706 /// let (ab, cd) = an_rope.split(2);
707 /// assert_eq!(ab, Rope::from(String::from("ab")));
708 /// assert_eq!(cd, Rope::from(String::from("cd")));
709 /// ```
710 pub fn split<M: Metric>(&self, index: M) -> (Rope, Rope)
711 where Self: Measured<M>
712 , NodeLink: Measured<M>
713 , String: Measured<M>
714 , str: Measured<M>
715 {
716 assert!(index <= self.measure());
717 let (l, r) = self.root.split(index);
718 (Rope::from(l), Rope::from(r))
719 }
720
721 /// Rebalances this entire `Rope`, returning a balanced `Rope`.
722 #[inline]
723 #[cfg(any(test, feature = "rebalance"))]
724 fn rebalance(&mut self) {
725 if self.is_balanced() {
726 // the rope is already balanced, do nothing
727 } else {
728 // rebalance the rope
729 // self.root = self.root.rebalance();
730 }
731 }
732
733 /// Returns true if this `Rope` is balanced.
734 ///
735 /// Balancing invariant:
736 /// the rope length needs to be less than _F_(rope_length) where F is fibonacci
737 #[inline]
738 #[cfg(any(test, feature = "rebalance"))]
739 fn is_balanced(&self) -> bool {
740 self.root.is_balanced()
741 }
742
743 unstable_iters! {
744 #[doc="Returns an iterator over all the strings in this `Rope`"]
745 #[inline]
746 pub fn strings<'a>(&'a self) -> impl Iterator<Item=&'a str> + 'a {
747 self.root.strings()
748 }
749
750 #[doc="Returns an iterator over all the lines of text in this `Rope`."]
751 pub fn lines<'a>(&'a self) -> impl Iterator<Item=RopeSlice<'a>> +'a {
752 { // create a new block here so the macro will bind the `use` stmt
753 use internals::IsLineEnding;
754 let last_idx = self.len() - 1;
755 Box::new(self.char_indices()
756 .filter_map(move |(i, c)|
757 if c.is_line_ending() { Some(i) }
758 // special case: slice to the end of the rope
759 // even if it doesn't end in a newline character
760 else if i == last_idx { Some(i + 1) }
761 else { None })
762 .scan(0, move |mut l, i| {
763 let last = *l;
764 *l = i + 1;
765 Some(self.slice(last..i))
766 }))
767 }
768 }
769 }
770 //
771 //
772 // /// Returns a move iterator over all the strings in this `Rope`
773 // ///
774 // /// Consumes `self`.
775 // #[cfg(feature = "unstable")]
776 // #[inline]
777 // pub fn into_strings<'a>(self) -> impl Iterator<Item=String> + 'a {
778 // self.root.into_strings()
779 // }
780 //
781 // /// Returns a move iterator over all the strings in this `Rope`
782 // ///
783 // /// Consumes `self`.
784 // #[cfg(not(feature = "unstable"))]
785 // #[inline]
786 // pub fn into_strings<'a>(self) -> Box<Iterator<Item=String> + 'a> {
787 // self.root.into_strings()
788 // }
789
790
791 str_iters! {
792 #[doc="Returns an iterator over all the bytes in this `Rope`.\n\
793 \nAs a Rope consists of a sequence of bytes, we can iterate \
794 through a rope by byte. This method returns such an iterator."]
795 #[inline]
796 impl bytes<u8> for Rope {}
797 #[doc="Returns an iterator over all the characters in this `Rope`.\n\
798 \nAs a `Rope` consists of valid UTF-8, we can iterate through a \
799 `Rope` by `char`. This method returns such an iterator. \n\
800 \nIt's important to remember that `char` represents a Unicode \
801 Scalar Value, and may not match your idea of what a \
802 'character' is. Iteration over grapheme clusters may be what \
803 you actually want."]
804 #[inline]
805 impl chars<char> for Rope {}
806 #[inline]
807 impl char_indices<(usize, char)> for Rope {}
808 #[inline]
809 impl split_whitespace<&'a str> for Rope {}
810 // #[inline]
811 // impl lines<&'a str> for Rope {}
812 }
813
814 unicode_seg_iters! {
815 #[doc=
816 "Returns an iterator over the [grapheme clusters][graphemes] of \
817 `self`.\n\
818
819 [graphemes]: \
820 http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries\
821 \n\
822 The iterator is over the *extended grapheme clusters*; as \
823 [UAX#29]\
824 (http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)\
825 recommends extended grapheme cluster boundaries for general \
826 processing."]
827 #[inline]
828 impl graphemes<&'a str> for Rope {}
829 #[doc=
830 "Returns an iterator over the words of `self`, separated on \
831 [UAX#29 word boundaries]\
832 (http://www.unicode.org/reports/tr29/#Word_Boundaries).\n\n\
833
834 Here, \"words\" are just those substrings which, after splitting on\
835 UAX#29 word boundaries, contain any alphanumeric characters. That \
836 is, the substring must contain at least one character with the \
837 [Alphabetic](http://unicode.org/reports/tr44/#Alphabetic) \
838 property, or with [General_Category=Number]\
839 (http://unicode.org/reports/tr44/#General_Category_Values)."]
840 #[inline]
841 impl unicode_words<&'a str> for Rope {}
842 #[doc=
843 "Returns an iterator over substrings of `self` separated on \
844 [UAX#29 word boundaries]\
845 (http://www.unicode.org/reports/tr29/#Word_Boundaries). \n\n\
846 The concatenation of the substrings returned by this function is \
847 just the original string."]
848 #[inline]
849 impl split_word_bounds<&'a str> for Rope {}
850 // #[inline]
851 // impl grapheme_indices<(usize, &'a str)> for Rope {}
852 // #[inline]
853 // impl split_word_bound_indices<(usize, &'a str)> for Rope {}
854 }
855
856 /// Returns an iterator over the grapheme clusters of `self` and their
857 /// byte offsets. See `graphemes()` for more information.
858 ///
859 /// # Examples
860 ///
861 /// ```
862 /// # use an_rope::Rope;
863 /// let rope = Rope::from("a̐éö̲\r\n");
864 /// let gr_inds = rope.grapheme_indices()
865 /// .collect::<Vec<(usize, &str)>>();
866 /// let b: &[_] = &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
867 ///
868 /// assert_eq!(&gr_inds[..], b);
869 /// ```
870 #[inline]
871 pub fn grapheme_indices(&self) -> internals::GraphemeIndices {
872 self.root.grapheme_indices()
873 }
874
875 /// Returns an iterator over substrings of `self`, split on UAX#29 word
876 /// boundaries, and their offsets. See `split_word_bounds()` for more
877 /// information.
878 ///
879 /// # Example
880 ///
881 /// ```
882 /// # use an_rope::Rope;
883 /// let rope = Rope::from("Brr, it's 29.3°F!");
884 /// let swi1 = rope.split_word_bound_indices()
885 /// .collect::<Vec<(usize, &str)>>();
886 /// let b: &[_] = &[ (0, "Brr"), (3, ","), (4, " "), (5, "it's")
887 /// , (9, " "), (10, "29.3"), (14, "°"), (16, "F")
888 /// , (17, "!")];
889 ///
890 /// assert_eq!(&swi1[..], b);
891 /// ```
892 #[inline]
893 pub fn split_word_bound_indices(&self) -> internals::UWordBoundIndices {
894 self.root.split_word_bound_indices()
895 }
896
897 /// Returns true if the bytes in `self` equal the bytes in `other`
898 #[inline]
899 fn bytes_eq<I>(&self, other: I) -> bool
900 where I: Iterator<Item=u8> {
901 self.bytes().zip(other).all(|(a, b)| a == b)
902 }
903
904 /// Returns an immutable slice of this `Rope` between the given indices.
905 ///
906 /// # Arguments
907 /// + `range`: A [`RangeArgument`](https://doc.rust-lang.org/nightly/collections/range/trait.RangeArgument.html)
908 /// specifying the range to slice. This can be produced by range syntax
909 /// like `..`, `a..`, `..b` or `c..d`.
910 ///
911 /// # Panics
912 /// If the start or end indices of the range to slice exceed the length of
913 /// this `Rope`.
914 ///
915 /// # Examples
916 /// ```ignore
917 // this doctest fails to link on my macbook for Secret Reasons.
918 // i'd really like to know why...
919 // - eliza, 12/23/2016
920 /// #![feature(collections)]
921 /// #![feature(collections_range)]
922 ///
923 /// extern crate collections;
924 /// extern crate an_rope;
925 /// # fn main() {
926 /// use collections::range::RangeArgument;
927 /// use an_rope::Rope;
928 ///
929 /// let rope = Rope::from("this is an example string");
930 /// assert_eq!(&rope.slice(4..6), "is");
931 /// # }
932 /// ```
933 #[inline]
934 #[cfg(feature = "unstable")]
935 pub fn slice<R>(&self, range: R) -> RopeSlice
936 where R: RangeArgument<usize> {
937 RopeSlice::new(&self.root, range)
938 }
939 #[cfg(not(feature = "unstable"))]
940 pub fn slice(&self, range: ops::Range<usize>) -> RopeSlice {
941 RopeSlice::new(&self.root, range)
942 }
943
944}
945
946impl convert::Into<Vec<u8>> for Rope {
947 fn into(self) -> Vec<u8> {
948 unimplemented!()
949 }
950
951}
952
953//-- comparisons ----------------------------------------------------
954impl cmp::Eq for Rope {}
955impl cmp::PartialEq for Rope {
956 /// A rope equals another rope if all the bytes in both are equal.
957 ///
958 /// # Examples
959 /// ```
960 /// use an_rope::Rope;
961 /// assert!(Rope::from("abcd") == Rope::from("abcd"));
962 /// ```
963 /// ```
964 /// use an_rope::Rope;
965 /// assert!(Rope::from("abcd") != Rope::from("ab"));
966 /// ```
967 /// ```
968 /// use an_rope::Rope;
969 /// assert!(Rope::from("abcd") != Rope::from("dcab"))
970 /// ```
971 #[inline]
972 fn eq(&self, other: &Rope) -> bool {
973 if self.len() == other.len() {
974 self.bytes_eq(other.bytes())
975 } else {
976 false
977 }
978 }
979}
980
981impl cmp::PartialEq<str> for Rope {
982 /// A rope equals a string if all the bytes in the string equal the rope's.
983 ///
984 /// # Examples
985 /// ```
986 /// use an_rope::Rope;
987 /// assert!(&Rope::from("abcd") == "abcd");
988 /// ```
989 /// ```
990 /// use an_rope::Rope;
991 /// assert!(&Rope::from("abcd") != "ab");
992 /// ```
993 /// ```
994 /// use an_rope::Rope;
995 /// assert!(&Rope::from("abcd") != "dcab");
996 /// ```
997 #[inline]
998 fn eq(&self, other: &str) -> bool {
999 if self.len() == other.len() {
1000 self.bytes_eq(other.bytes())
1001 } else {
1002 false
1003 }
1004 }
1005}
1006
1007
1008impl cmp::PartialEq<String> for Rope {
1009 /// A rope equals a string if all the bytes in the string equal the rope's.
1010 ///
1011 /// # Examples
1012 /// ```
1013 /// use an_rope::Rope;
1014 /// assert!(Rope::from("abcd") == String::from("abcd"));
1015 /// ```
1016 /// ```
1017 /// use an_rope::Rope;
1018 /// assert!(Rope::from("abcd") != String::from("ab"));
1019 /// ```
1020 /// ```
1021 /// use an_rope::Rope;
1022 /// assert!(Rope::from("abcd") != String::from("dcab"));
1023 /// ```
1024 #[inline]
1025 fn eq(&self, other: &String) -> bool {
1026 if self.len() == other.len() {
1027 self.bytes_eq(other.bytes())
1028 } else {
1029 false
1030 }
1031 }
1032}
1033
1034
1035//-- concatenation --------------------------------------------------
1036impl<'a> ops::Add for &'a Rope {
1037 type Output = Rope;
1038 /// Non-destructively concatenate two `Rope`s, returning a new `Rope`.
1039 ///
1040 /// # Examples
1041 /// ```
1042 /// use an_rope::Rope;
1043 /// let rope = Rope::from(String::from("ab"));
1044 /// assert_eq!( &rope + &Rope::from(String::from("cd"))
1045 /// , Rope::from(String::from("abcd")) );
1046 /// ```
1047 #[inline] fn add(self, other: Self) -> Rope { self.append(other) }
1048
1049}
1050
1051impl ops::Add for Rope {
1052 type Output = Rope;
1053 /// Non-destructively concatenate two `Rope`s, returning a new `Rope`.
1054 ///
1055 /// # Examples
1056 /// ```
1057 /// use an_rope::Rope;
1058 /// let rope = Rope::from(String::from("ab"));
1059 /// assert_eq!( rope + Rope::from(String::from("cd"))
1060 /// , Rope::from(String::from("abcd")) );
1061 /// ```
1062 #[inline] fn add(self, other: Self) -> Rope { self.append(&other) }
1063}
1064
1065impl ops::Add<String> for Rope {
1066 type Output = Rope;
1067 /// Non-destructively concatenate a `Rope` and a `String`.
1068 ///
1069 /// Returns a new `Rope`
1070 ///
1071 /// # Examples
1072 /// ```
1073 /// use an_rope::Rope;
1074 /// let rope = Rope::from(String::from("ab"));
1075 /// assert_eq!( rope + String::from("cd")
1076 /// , Rope::from(String::from("abcd")));
1077 /// ```
1078 #[inline] fn add(self, other: String) -> Rope {
1079 self.append(&Rope::from(other))
1080 }
1081}
1082
1083
1084impl<'a, 'b> ops::Add<&'b str> for &'a Rope {
1085 type Output = Rope;
1086 /// Non-destructively concatenate a `Rope` and an `&str`.
1087 ///
1088 /// Returns a new `Rope`
1089 ///
1090 /// # Examples
1091 /// ```
1092 /// use an_rope::Rope;
1093 /// let rope = Rope::from(String::from("ab"));
1094 /// assert_eq!( &rope + "cd"
1095 /// , Rope::from(String::from("abcd")));
1096 /// ```
1097 #[inline] fn add(self, other: &'b str) -> Rope {
1098 self.append(&Rope::from(other.to_owned()))
1099 }
1100
1101}
1102
1103impl<'a> ops::Add<&'a str> for Rope {
1104 type Output = Rope;
1105 /// Non-destructively concatenate a `Rope` and an `&str`.
1106 ///
1107 /// Returns a new `Rope`
1108 ///
1109 /// # Examples
1110 /// ```
1111 /// use an_rope::Rope;
1112 /// let rope = Rope::from(String::from("ab"));
1113 /// assert_eq!( rope + "cd"
1114 /// , Rope::from(String::from("abcd")));
1115 /// ```
1116 #[inline] fn add(self, other: &'a str) -> Rope {
1117 self.append(&Rope::from(other.to_owned()))
1118 }
1119
1120}
1121
1122impl ops::Index<usize> for Rope {
1123 type Output = str;
1124
1125 /// Recursively index the Rope to return the `i` th character.
1126 ///
1127 /// # Examples
1128 /// ```
1129 /// use an_rope::Rope;
1130 /// let an_rope = Rope::from(String::from("abcd"));
1131 /// assert_eq!(&an_rope[0], "a");
1132 /// assert_eq!(&an_rope[1], "b");
1133 /// assert_eq!(&an_rope[2], "c");
1134 /// assert_eq!(&an_rope[3], "d");
1135 /// ```
1136 ///
1137 /// # Time complexity
1138 /// _O_(log _n_)
1139 ///
1140 #[inline]
1141 fn index(&self, i: usize) -> &str {
1142 &self.root[i]
1143 }
1144}
1145
1146//-- slicing operators ----------------------------------------------
1147impl ops::Index<ops::Range<usize>> for Rope {
1148 type Output = str;
1149
1150 // Index a substring
1151 fn index(&self, _i: ops::Range<usize>) -> &str {
1152 unimplemented!()
1153 }
1154}
1155
1156impl ops::Index<ops::RangeTo<usize>> for Rope {
1157 type Output = str;
1158
1159 fn index(&self, _i: ops::RangeTo<usize>) -> &str {
1160 unimplemented!()
1161 }
1162}
1163
1164impl ops::Index<ops::RangeFrom<usize>> for Rope {
1165 type Output = str;
1166
1167 fn index(&self, _i: ops::RangeFrom<usize>) -> &str {
1168 unimplemented!()
1169 }
1170}
1171
1172impl ops::IndexMut<ops::Range<usize>> for Rope {
1173 fn index_mut(&mut self, _i: ops::Range<usize>) -> &mut str {
1174 unimplemented!()
1175 }
1176}
1177
1178impl ops::IndexMut<ops::RangeTo<usize>> for Rope {
1179 fn index_mut(&mut self, _i: ops::RangeTo<usize>) -> &mut str {
1180 unimplemented!()
1181 }
1182}
1183
1184impl ops::IndexMut<ops::RangeFrom<usize>> for Rope {
1185 fn index_mut(&mut self, _i: ops::RangeFrom<usize>) -> &mut str {
1186 unimplemented!()
1187 }
1188}
1189
1190// impl<'a> Borrow<RopeSlice<'a>> for &'a Rope {
1191// fn borrow(&self) -> &RopeSlice<'a> {
1192// unimplemented!()
1193// }
1194// }
1195
1196// impl<A> iter::Extend<A> for Rope
1197// where Rope: iter::FromIterator<A>{
1198//
1199// fn extend<B>(&mut self, iter: B)
1200// where B: IntoIterator<Item=A> {
1201//
1202// self.append(&(iter.into_iter().collect()));
1203//
1204// }
1205//
1206// }
1207
1208impl iter::FromIterator<char> for Rope {
1209
1210 fn from_iter<I>(iter: I) -> Rope
1211 where I: IntoIterator<Item=char> {
1212 let s: String = iter.into_iter().collect();
1213 Rope::from(s)
1214
1215 }
1216
1217}
1218
1219impl iter::FromIterator<String> for Rope {
1220
1221 fn from_iter<I>(iter: I) -> Rope
1222 where I: IntoIterator<Item=String> {
1223 iter.into_iter().fold(Rope::new(), |acc, x| acc + x)
1224 }
1225
1226}
1227
1228impl iter::FromIterator<Rope> for Rope {
1229
1230 fn from_iter<I>(iter: I) -> Rope
1231 where I: IntoIterator<Item=Rope> {
1232 iter.into_iter().fold(Rope::new(), |acc, x| acc + x)
1233 }
1234
1235}
1236
1237impl<'a> iter::FromIterator<&'a char> for Rope {
1238
1239 fn from_iter<I>(iter: I) -> Rope
1240 where I: IntoIterator<Item=&'a char> {
1241 let s: String = iter.into_iter().fold(String::new(), |mut acc, x| {acc.push(*x); acc});
1242 Rope::from(s)
1243 }
1244
1245}
1246
1247impl<'a> iter::FromIterator<&'a str> for Rope {
1248
1249 fn from_iter<I>(iter: I) -> Rope
1250 where I: IntoIterator<Item=&'a str> {
1251 iter.into_iter().fold(Rope::new(), |acc, x| acc + x)
1252 }
1253
1254}