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
//! Iterators over a `Rope`'s data.
//!
//! All iterators here can also be used with `RopeSlice`'s.  When used
//! with a `RopeSlice`, they iterate over only the data that the
//! `RopeSlice` refers to.  For the line, chunk, and grapheme iterators,
//! the data of the first and last yielded item will be truncated to
//! match the `RopeSlice`.

use std::str;
use std::sync::Arc;

use segmentation::{GraphemeSegmenter, SegmenterUtils};
use tree::Node;
use slice::RopeSlice;

//==========================================================

/// An iterator over a `Rope`'s bytes.
pub struct Bytes<'a, S: 'a + GraphemeSegmenter> {
    chunk_iter: Chunks<'a, S>,
    cur_chunk: str::Bytes<'a>,
}

impl<'a, S: 'a + GraphemeSegmenter> Bytes<'a, S> {
    pub(crate) fn new(node: &Arc<Node<S>>) -> Bytes<S> {
        Bytes {
            chunk_iter: Chunks::new(node),
            cur_chunk: "".bytes(),
        }
    }

    pub(crate) fn new_with_range(
        node: &Arc<Node<S>>,
        start_char: usize,
        end_char: usize,
    ) -> Bytes<S> {
        Bytes {
            chunk_iter: Chunks::new_with_range(node, start_char, end_char),
            cur_chunk: "".bytes(),
        }
    }
}

impl<'a, S: 'a + GraphemeSegmenter> Iterator for Bytes<'a, S> {
    type Item = u8;

    fn next(&mut self) -> Option<u8> {
        loop {
            if let Some(c) = self.cur_chunk.next() {
                return Some(c);
            } else if let Some(chunk) = self.chunk_iter.next() {
                self.cur_chunk = chunk.bytes();
                continue;
            } else {
                return None;
            }
        }
    }
}

//==========================================================

/// An iterator over a `Rope`'s chars.
pub struct Chars<'a, S: 'a + GraphemeSegmenter> {
    chunk_iter: Chunks<'a, S>,
    cur_chunk: str::Chars<'a>,
}

impl<'a, S: 'a + GraphemeSegmenter> Chars<'a, S> {
    pub(crate) fn new(node: &Arc<Node<S>>) -> Chars<S> {
        Chars {
            chunk_iter: Chunks::new(node),
            cur_chunk: "".chars(),
        }
    }

    pub(crate) fn new_with_range(
        node: &Arc<Node<S>>,
        start_char: usize,
        end_char: usize,
    ) -> Chars<S> {
        Chars {
            chunk_iter: Chunks::new_with_range(node, start_char, end_char),
            cur_chunk: "".chars(),
        }
    }
}

impl<'a, S: 'a + GraphemeSegmenter> Iterator for Chars<'a, S> {
    type Item = char;

    fn next(&mut self) -> Option<char> {
        loop {
            if let Some(c) = self.cur_chunk.next() {
                return Some(c);
            } else if let Some(chunk) = self.chunk_iter.next() {
                self.cur_chunk = chunk.chars();
                continue;
            } else {
                return None;
            }
        }
    }
}

//==========================================================

/// An iterator over a `Rope`'s grapheme clusters.
///
/// The grapheme clusters returned are based on the `Rope`'s [grapheme segmenter](segmentation/index.html),
/// which by default is [`DefaultSegmenter`](segmentation/struct.DefaultSegmenter.html).
pub struct Graphemes<'a, S: 'a + GraphemeSegmenter> {
    chunk_iter: Chunks<'a, S>,
    cur_chunk: &'a str,
}

impl<'a, S: 'a + GraphemeSegmenter> Graphemes<'a, S> {
    pub(crate) fn new(node: &Arc<Node<S>>) -> Graphemes<S> {
        Graphemes {
            chunk_iter: Chunks::new(node),
            cur_chunk: "",
        }
    }

    pub(crate) fn new_with_range(
        node: &Arc<Node<S>>,
        start_char: usize,
        end_char: usize,
    ) -> Graphemes<S> {
        Graphemes {
            chunk_iter: Chunks::new_with_range(node, start_char, end_char),
            cur_chunk: "",
        }
    }
}

impl<'a, S: 'a + GraphemeSegmenter> Iterator for Graphemes<'a, S> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        loop {
            if !self.cur_chunk.is_empty() {
                let next_idx = S::next_break(0, self.cur_chunk);
                let g = &self.cur_chunk[..next_idx];
                self.cur_chunk = &self.cur_chunk[next_idx..];
                return Some(g);
            } else if let Some(chunk) = self.chunk_iter.next() {
                self.cur_chunk = chunk;
                continue;
            } else {
                return None;
            }
        }
    }
}

//==========================================================

/// An iterator over a `Rope`'s lines.
///
/// The returned lines include the line-break at the end.
///
/// The last line is returned even if blank, in which case it
/// is returned as an empty slice.
pub struct Lines<'a, S: 'a + GraphemeSegmenter> {
    node: &'a Arc<Node<S>>,
    start_char: usize,
    end_char: usize,
    line_idx: usize,
}

impl<'a, S: 'a + GraphemeSegmenter> Lines<'a, S> {
    pub(crate) fn new(node: &Arc<Node<S>>) -> Lines<S> {
        Lines {
            node: node,
            start_char: 0,
            end_char: node.text_info().chars as usize,
            line_idx: 0,
        }
    }

    pub(crate) fn new_with_range(
        node: &Arc<Node<S>>,
        start_char: usize,
        end_char: usize,
    ) -> Lines<S> {
        Lines {
            node: node,
            start_char: start_char,
            end_char: end_char,
            line_idx: node.char_to_line(start_char),
        }
    }
}

impl<'a, S: 'a + GraphemeSegmenter> Iterator for Lines<'a, S> {
    type Item = RopeSlice<'a, S>;

    fn next(&mut self) -> Option<RopeSlice<'a, S>> {
        if self.line_idx > self.node.line_break_count() {
            return None;
        } else {
            let a = self.node.line_to_char(self.line_idx).max(self.start_char);

            // Early out if we're past the specified end char
            if a > self.end_char {
                self.line_idx = self.node.line_break_count() + 1;
                return None;
            }

            let b = if self.line_idx < self.node.line_break_count() {
                self.node.line_to_char(self.line_idx + 1)
            } else {
                self.node.char_count()
            }.min(self.end_char);

            self.line_idx += 1;

            return Some(RopeSlice::new_with_range(self.node, a, b));
        }
    }
}

//==========================================================

/// An iterator over a `Rope`'s contiguous `str` chunks.
///
/// Internally, each `Rope` stores text as a segemented collection of utf8
/// strings. This iterator iterates over those segments, returning a
/// `&str` slice for each one.  It is useful for situations such as:
///
/// - Writing a rope's text data to disk.
/// - Streaming a rope's text data somewhere.
/// - Saving a rope to a non-utf8 encoding, doing the encoding conversion
///   incrementally as you go.
/// - Writing custom iterators over a rope's text data.
///
/// There are only two API guarantees about the chunks this iterator yields:
///
/// 1. They are in-order, non-overlapping, and complete (i.e. the entire
///    text is iterated over in order).
/// 2. Grapheme clusters are _never_ split between chunks.  (Grapheme
///    clusters in this case are defined as the extended grapheme
///    clusters in [Unicode Standard Annex #29](https://www.unicode.org/reports/tr29/))
///
/// There are no other API guarantees.  For example, chunks can
/// theoretically be of any size (including empty), line breaks and chunk
/// boundaries have no guaranteed relationship, etc.
///
/// The converse of this API is [`RopeBuilder`](../struct.RopeBuilder.html),
/// which is useful for efficiently streaming text data _into_ a rope.
pub struct Chunks<'a, S: 'a + GraphemeSegmenter> {
    node_stack: Vec<&'a Arc<Node<S>>>,
    start: usize,
    end: usize,
    idx: usize,
}

impl<'a, S: 'a + GraphemeSegmenter> Chunks<'a, S> {
    pub(crate) fn new(node: &Arc<Node<S>>) -> Chunks<S> {
        Chunks {
            node_stack: vec![node],
            start: 0,
            end: node.text_info().bytes as usize,
            idx: 0,
        }
    }

    pub(crate) fn new_with_range(
        node: &Arc<Node<S>>,
        start_char: usize,
        end_char: usize,
    ) -> Chunks<S> {
        Chunks {
            node_stack: vec![node],
            start: node.char_to_byte(start_char),
            end: node.char_to_byte(end_char),
            idx: 0,
        }
    }
}

impl<'a, S: 'a + GraphemeSegmenter> Iterator for Chunks<'a, S> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        if self.idx >= self.end {
            return None;
        }

        loop {
            if let Some(node) = self.node_stack.pop() {
                match **node {
                    Node::Leaf(ref text) => {
                        let start_byte = if self.start <= self.idx {
                            0
                        } else {
                            self.start - self.idx
                        };
                        let end_byte = if self.end >= (self.idx + text.len()) {
                            text.len()
                        } else {
                            self.end - self.idx
                        };
                        self.idx += text.len();
                        return Some(&text[start_byte..end_byte]);
                    }

                    Node::Internal(ref children) => {
                        // Find the first child that isn't before `self.start`,
                        // updating `self.idx` as we go.
                        let mut child_i = 0;
                        for inf in children.info().iter() {
                            if (self.idx + inf.bytes as usize) > self.start {
                                break;
                            } else {
                                self.idx += inf.bytes as usize;
                                child_i += 1;
                            }
                        }
                        // Push relevant children to the stack.
                        for child in (&children.nodes()[child_i..]).iter().rev() {
                            self.node_stack.push(child);
                        }
                    }
                }
            } else {
                return None;
            }
        }
    }
}

//===========================================================

#[cfg(test)]
mod tests {
    use unicode_segmentation::UnicodeSegmentation;
    use Rope;

    const TEXT: &str = "\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        Hello there!  How're you doing?  It's a fine day, \
                        isn't it?  Aren't you glad we're alive?\r\n\
                        こんにちは!元気ですか?日はいいですね。\
                        私たちが生きだって嬉しいではないか?\r\n\
                        ";

    #[test]
    fn bytes_01() {
        let r = Rope::from_str(TEXT);
        for (br, bt) in r.bytes().zip(TEXT.bytes()) {
            assert_eq!(br, bt);
        }
    }

    #[test]
    fn chars_01() {
        let r = Rope::from_str(TEXT);
        for (cr, ct) in r.chars().zip(TEXT.chars()) {
            assert_eq!(cr, ct);
        }
    }

    #[test]
    fn graphemes_01() {
        let r = Rope::from_str(TEXT);
        for (gr, gt) in r.graphemes()
            .zip(UnicodeSegmentation::graphemes(TEXT, true))
        {
            assert_eq!(gr, gt);
        }
    }

    #[test]
    fn lines_01() {
        let r = Rope::from_str(TEXT);

        assert_eq!(34, r.lines().count());

        let mut lines = r.lines();

        assert_eq!("\r\n", lines.next().unwrap());

        for _ in 0..16 {
            assert_eq!(
                "Hello there!  How're you doing?  It's a fine day, \
                 isn't it?  Aren't you glad we're alive?\r\n",
                lines.next().unwrap()
            );
            assert_eq!(
                "こんにちは!元気ですか?日はいいですね。\
                 私たちが生きだって嬉しいではないか?\r\n",
                lines.next().unwrap()
            );
        }

        assert_eq!("", lines.next().unwrap());
        assert!(lines.next().is_none());
    }

    #[test]
    fn lines_02() {
        let text = "Hello there!\nHow goes it?";
        let r = Rope::from_str(text);

        assert_eq!(2, r.lines().count());

        let mut lines = r.lines();
        assert_eq!("Hello there!\n", lines.next().unwrap());
        assert_eq!("How goes it?", lines.next().unwrap());
        assert!(lines.next().is_none());
    }

    #[test]
    fn chunks_01() {
        let r = Rope::from_str(TEXT);

        let mut idx = 0;
        for chunk in r.chunks() {
            assert_eq!(chunk, &TEXT[idx..(idx + chunk.len())]);
            idx += chunk.len();
        }
    }

    #[test]
    fn bytes_sliced_01() {
        let r = Rope::from_str(TEXT);

        let s_start = 116;
        let s_end = 331;
        let s_start_byte = r.char_to_byte(s_start);
        let s_end_byte = r.char_to_byte(s_end);

        let s1 = r.slice(s_start..s_end);
        let s2 = &TEXT[s_start_byte..s_end_byte];

        for (br, bt) in s1.bytes().zip(s2.bytes()) {
            assert_eq!(br, bt);
        }
    }

    #[test]
    fn chars_sliced_01() {
        let r = Rope::from_str(TEXT);

        let s_start = 116;
        let s_end = 331;
        let s_start_byte = r.char_to_byte(s_start);
        let s_end_byte = r.char_to_byte(s_end);

        let s1 = r.slice(s_start..s_end);
        let s2 = &TEXT[s_start_byte..s_end_byte];

        for (cr, ct) in s1.chars().zip(s2.chars()) {
            assert_eq!(cr, ct);
        }
    }

    #[test]
    fn graphemes_sliced_01() {
        let r = Rope::from_str(TEXT);

        let s_start = 116;
        let s_end = 331;
        let s_start_byte = r.char_to_byte(s_start);
        let s_end_byte = r.char_to_byte(s_end);

        let s1 = r.slice(s_start..s_end);
        let s2 = &TEXT[s_start_byte..s_end_byte];

        for (gr, gt) in s1.graphemes().zip(UnicodeSegmentation::graphemes(s2, true)) {
            assert_eq!(gr, gt);
        }
    }

    #[test]
    fn graphemes_sliced_02() {
        let text = "\r\n\r\n\r\n\r\n\r\n\r\n\r\n";
        let r = Rope::from_str(text);

        let s1 = r.slice(5..11);
        let s2 = &text[5..11];

        assert_eq!(4, s1.graphemes().count());

        for (gr, gt) in s1.graphemes().zip(UnicodeSegmentation::graphemes(s2, true)) {
            assert_eq!(gr, gt);
        }
    }

    #[test]
    fn lines_sliced_01() {
        let r = Rope::from_str(TEXT);

        let s_start = 116;
        let s_end = 331;
        let s_start_byte = r.char_to_byte(s_start);
        let s_end_byte = r.char_to_byte(s_end);

        let s1 = r.slice(s_start..s_end);
        let s2 = &TEXT[s_start_byte..s_end_byte];

        for (liner, linet) in s1.lines().zip(s2.lines()) {
            assert_eq!(liner.to_string().trim_right(), linet);
        }
    }

    #[test]
    fn chunks_sliced_01() {
        let r = Rope::from_str(TEXT);

        let s_start = 116;
        let s_end = 331;
        let s_start_byte = r.char_to_byte(s_start);
        let s_end_byte = r.char_to_byte(s_end);

        let s1 = r.slice(s_start..s_end);
        let s2 = &TEXT[s_start_byte..s_end_byte];

        let mut idx = 0;
        for chunk in s1.chunks() {
            assert_eq!(chunk, &s2[idx..(idx + chunk.len())]);
            idx += chunk.len();
        }
    }
}