segmented_string 0.1.0

an immutable string type built from array segments, similar to clojure's persistent vector, with unicode grapheme/width support
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
use alloc::boxed::Box;
use alloc::fmt;
use smol_str::SmolStr;

use crate::string::StringSegment;


// an array of A, filled in from the left (0 up), with a byte length & char length
#[derive(Clone, PartialEq)]
pub struct SizedSegment<const WIDTH: usize, A> {
    span: Box<[Option<A>; WIDTH]>,
    length_and_depth: u32,  // length in bytes (u29 = 512MB max), and depth (for branches) (u3 = 0-7)
    char_length: u32,  // in grapheme clusters
}

impl<const WIDTH: usize, A> Default for SizedSegment<WIDTH, A> {
    fn default() -> SizedSegment<WIDTH, A> {
        // i'm not sure why it couldn't figure out that None is const!
        SizedSegment { span: Box::new([const { None }; WIDTH]), length_and_depth: 0, char_length: 0 }
    }
}

impl<const WIDTH: usize, A: fmt::Debug> fmt::Debug for SizedSegment<WIDTH, A> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}:{})[ ", self.length(), self.char_length)?;
        for (i, slot) in self.span.as_ref().iter().flatten().enumerate() {
            if i > 0 { write!(f, ", ")?; }
            write!(f, "{:?}", slot)?;
        }
        write!(f, " ]")
    }
}

impl<const WIDTH: usize, A> SizedSegment<WIDTH, A> {
    pub fn length(&self) -> usize { (self.length_and_depth & 0x1fff_ffff) as usize }
    pub fn depth(&self) -> usize { (self.length_and_depth >> 29) as usize }

    pub fn add_length(&mut self, add: usize) {
        assert!(self.length() + add < (1 << 29), "string too long");
        self.length_and_depth += add as u32;
    }

    pub fn set_depth(&mut self, depth: usize) {
        assert!(depth < 8, "string complexity too deep!");
        self.length_and_depth = (self.length() | (depth << 29)) as u32;
    }

    // return the A if this segment is full
    pub fn append(&mut self, item: A, length: usize, char_length: usize) -> Option<A> {
        assert!(self.length() + length < (1 << 29), "string too long");
        if let Some(slot) = self.span.iter_mut().find(|slot| slot.is_none()) {
            self.length_and_depth += length as u32;
            self.char_length += char_length as u32;
            *slot = Some(item);
            None
        } else {
            Some(item)
        }
    }

    pub fn last_slot_mut(&mut self) -> Option<&mut A> {
        self.span.iter_mut().flatten().last()
    }
}


// a span of string segments stored in the leaf nodes of a Segment tree.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LeafSegment<const WIDTH: usize> {
    segment: SizedSegment<WIDTH, StringSegment>,
}

impl<const WIDTH: usize> LeafSegment<WIDTH> {
    pub fn from_smol_str(s: &SmolStr, char_length: usize) -> LeafSegment<WIDTH> {
        let mut ret = LeafSegment::default();
        ret.append(StringSegment::new_with_length(s, char_length));
        ret
    }

    // return the StringSegment if the leaf is full
    pub fn append(&mut self, ss: StringSegment) -> Option<StringSegment> {
        let length = ss.string.len();
        let char_length = ss.char_length;
        self.segment.append(ss, length, char_length)
    }

    // add as much of `s` as will fit in the last partial segment, and return how much was taken in bytes & chars.
    pub fn append_in_place(&mut self, s: &str, max_segment: usize) -> (usize, usize) {
        let (bytes, chars) = self.segment.last_slot_mut().map_or((0, 0), |ss| ss.append_in_place(s, max_segment));
        self.segment.add_length(bytes);
        self.segment.char_length += chars as u32;
        (bytes, chars)
    }

    // find the (index, char_start) of the StringSegment holding this char (offset from 0), if any
    pub fn find_index(&self, char_offset: usize) -> Option<(usize, usize)> {
        let mut char_start = 0;
        for (index, ss) in self.segment.span.iter().flatten().enumerate() {
            if char_offset < char_start + ss.char_length {
                return Some((index, char_start));
            }
            char_start += ss.char_length;
        }
        None
    }

    // find the grapheme cluster at this offset (from 0)
    pub fn get(&self, char_offset: usize) -> Option<&str> {
        self.find_index(char_offset).and_then(|(index, char_start)| {
            let offset = char_offset - char_start;
            self.segment.span[index].as_ref().unwrap().get(offset)
        })
    }
}


#[derive(Clone, Debug, Default, PartialEq)]
pub struct BranchSegment<const WIDTH: usize> {
    segment: SizedSegment<WIDTH, Segment<WIDTH>>,
}

impl<const WIDTH: usize> BranchSegment<WIDTH> {
    fn new_child(&self) -> Segment<WIDTH> {
        if self.segment.depth() == 0 {
            Segment::Leaf(Default::default())
        } else {
            let mut branch = BranchSegment::default();
            branch.segment.set_depth(self.segment.depth() - 1);
            Segment::Branch(branch)
        }
    }

    pub fn append(&mut self, ss: StringSegment) -> Option<StringSegment> {
        assert!(self.segment.length() + ss.string.len() < (1 << 29), "string too long");

        // ensure at least one slot exists
        if self.segment.span[0].is_none() {
            self.segment.append(self.new_child(), 0, 0);
        }

        // pass it to the next level
        let length = ss.string.len();
        let char_length = ss.char_length;
        let slot = self.segment.last_slot_mut().unwrap();
        if let Some(ss) = slot.append(ss) {
            // failed! lower levels are full. is this level full too?
            if self.segment.append(self.new_child(), 0, 0).is_some() {
                // whole subtree is full. fail up!
                Some(ss)
            } else {
                // must work this time!
                self.segment.add_length(length);
                self.segment.char_length += char_length as u32;
                self.segment.last_slot_mut().unwrap().append(ss)
            }
        } else {
            self.segment.add_length(length);
            self.segment.char_length += char_length as u32;
            None
        }
    }

    // add as much of `s` as will fit in the last partial segment, and return how much was taken, in bytes & chars.
    pub fn append_in_place(&mut self, s: &str, max_segment: usize) -> (usize, usize) {
        let (bytes, chars) = self.segment.last_slot_mut().map_or((0, 0), |slot| slot.append_in_place(s, max_segment));
        self.segment.add_length(bytes);
        self.segment.char_length += chars as u32;
        (bytes, chars)
    }

    pub fn add_segment(&mut self, segment: Segment<WIDTH>) -> Option<Segment<WIDTH>> {
        let length = segment.len();
        let char_length = segment.char_len();
        self.segment.append(segment, length, char_length)
    }
}


#[derive(Clone, PartialEq)]
pub enum Segment<const WIDTH: usize> {
    Branch(BranchSegment<WIDTH>),
    Leaf(LeafSegment<WIDTH>),
}

impl<const WIDTH: usize> fmt::Debug for Segment<WIDTH> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Segment::Branch(branch) => write!(f, "{:?}", branch.segment),
            Segment::Leaf(leaf) => write!(f, "{:?}", leaf.segment),
        }
    }
}

impl<const WIDTH: usize> Segment<WIDTH> {
    pub fn len(&self) -> usize {
        match self {
            Segment::Leaf(leaf) => leaf.segment.length(),
            Segment::Branch(branch) => branch.segment.length(),
        }
    }

    pub fn char_len(&self) -> usize {
        match self {
            Segment::Leaf(leaf) => leaf.segment.char_length as usize,
            Segment::Branch(branch) => branch.segment.char_length as usize,
        }
    }

    // returns the string segment if all slots are full
    pub fn append(&mut self, ss: StringSegment) -> Option<StringSegment> {
        match self {
            Segment::Leaf(leaf) => leaf.append(ss),
            Segment::Branch(branch) => branch.append(ss),
        }
    }

    // add as much of `s` as will fit in the last partial segment, and return how much was taken in bytes & chars.
    pub fn append_in_place(&mut self, s: &str, max_segment: usize) -> (usize, usize) {
        match self {
            Segment::Leaf(leaf) => leaf.append_in_place(s, max_segment),
            Segment::Branch(branch) => branch.append_in_place(s, max_segment),
        }
    }

    // create a new segment level above this one, and move this one into it
    pub fn add_level(self) -> Segment<WIDTH> {
        let next_depth = match self {
            Segment::Leaf(_) => 0,
            Segment::Branch(ref branch) => branch.segment.depth() + 1,
        };
        let mut branch = BranchSegment::default();
        branch.segment.set_depth(next_depth);
        branch.add_segment(self);
        Segment::Branch(branch)
    }

    // append a string segment, possibly returning a new segment if the tree had to grow deeper
    // (this is really only used by tests)
    #[cfg(test)]
    pub fn with_append_segment(mut self, ss: StringSegment) -> Segment<WIDTH> {
        if let Some(ss) = self.append(ss) {
            let mut new_root = self.add_level();
            assert!(new_root.append(ss).is_none(), "contract violation!");
            new_root
        } else {
            self
        }
    }

    // given a char offset, find the LeafSegment that holds that char, and the
    // char position the LeafSegment starts at.
    pub fn find_leaf(&self, char_offset: usize, position: usize) -> Option<(&'_ LeafSegment<WIDTH>, usize)> {
        match self {
            Segment::Leaf(leaf) => {
                (char_offset < leaf.segment.char_length as usize).then_some((leaf, position))
            },
            Segment::Branch(branch) => {
                if char_offset >= branch.segment.char_length as usize { return None; }
                let mut char_start = 0;
                for s in branch.segment.span.iter().flatten() {
                    if char_offset < char_start + s.char_len() {
                        return s.find_leaf(char_offset - char_start, position + char_start);
                    }
                    char_start += s.char_len();
                }
                None
            },
        }
    }

    // given a char offset, find the LeafSegment, index of the string segment
    // within it, and the starting char position of that string segment.
    pub fn find_string_segment(&self, char_offset: usize) -> Option<(&'_ LeafSegment<WIDTH>, usize, usize)> {
        self.find_leaf(char_offset, 0).and_then(|(leaf, position)| {
            leaf.find_index(char_offset - position).map(|(index, str_position)| {
                (leaf, index, position + str_position)
            })
        })
    }

    pub fn iter_strings(&self, char_start: usize, char_end: usize) -> SegmentStringIterator<'_, WIDTH> {
        let segment_iter = SegmentIterator::spanning(self, char_start, char_end);
        SegmentStringIterator { segment_iter, char_start, char_end }
    }

    pub fn get(&self, char_offset: usize) -> Option<&str> {
        self.find_leaf(char_offset, 0).and_then(|(leaf, position)| leaf.get(char_offset - position))
    }

    pub fn substr_equals<const W: usize>(
        &self,
        char_start: usize,
        char_end: usize,
        other: &Segment<W>,
        other_start: usize,
        other_end: usize
    ) -> bool {
        // iterate over the two strings together, which is a bit tricky!
        // remainder is the chunk of iter2's last string that hasn't been tested yet.
        let mut iter2 = other.iter_strings(other_start, other_end);
        let mut remainder: Option<&str> = None;
        for s1 in self.iter_strings(char_start, char_end) {
            let mut index = 0;
            while index < s1.len() {
                remainder = remainder.or_else(|| iter2.next());
                if let Some(s2) = remainder {
                    let len = s2.len().min(s1.len() - index);
                    if s1[index .. (index + len)] != s2[..len] { return false; }
                    index += len;
                    remainder = if len == s2.len() { None } else { Some(&s2[len..]) };
                } else {
                    return false;
                }
            }
        }
        // only if we finished:
        remainder.is_none() && iter2.next().is_none()
    }

    pub fn substr_equals_str(&self, char_start: usize, char_end: usize, other: &str) -> bool {
        let mut other_start = 0;
        for ss in self.iter_strings(char_start, char_end) {
            let other_end = other_start + ss.len();
            if other_end > other.len() || &other[other_start .. other_end] != ss { return false; }
            other_start += ss.len();
        }
        other_start == other.len()
    }
}


pub struct SegmentIterator<'a, const WIDTH: usize> {
    segment: &'a Segment<WIDTH>,
    // starting & ending char position for iteration:
    start_position: usize,
    end_position: usize,
    // which leaf are we in on the starting side, and which string segment:
    start_leaf: Option<&'a LeafSegment<WIDTH>>,
    start_index: usize,
    // same for the ending side:
    end_leaf: Option<&'a LeafSegment<WIDTH>>,
    end_index: usize,
}

impl<'a, const WIDTH: usize> SegmentIterator<'a, WIDTH> {
    // return an iterator between a start & end offset, with inclusive start
    // and exclusive end, as usual. the iterator returns full string segment
    // each time, so you need to call start_skip() and end_skip() to know how
    // many chars to skip from the starting and ending segments.
    pub fn spanning(
        segment: &'a Segment<WIDTH>,
        start_position: usize,
        end_position: usize
    ) -> SegmentIterator<'a, WIDTH> {
        SegmentIterator {
            segment,
            start_position,
            end_position,
            start_leaf: None,
            start_index: 0,
            end_leaf: None,
            end_index: 0,
        }
    }
}

// the iterator returns a StringSegment and the char position that it starts at.
impl<'a, const WIDTH: usize> Iterator for SegmentIterator<'a, WIDTH> {
    type Item = (&'a StringSegment, usize);

    fn next(&mut self) -> Option<Self::Item> {
        if self.start_position >= self.end_position { return None; }
        if self.start_leaf.is_none() {
            if let Some((leaf, index, start_position)) = self.segment.find_string_segment(self.start_position) {
                self.start_leaf = Some(leaf);
                self.start_index = index;
                self.start_position = start_position;
            } else {
                return None;
            }
        }

        let leaf = self.start_leaf.unwrap();
        if let Some(ss) = leaf.segment.span[self.start_index].as_ref() {
            let position = self.start_position;
            self.start_position += ss.char_length;
            self.start_index += 1;

            if self.start_index >= WIDTH || leaf.segment.span[self.start_index].is_none() {
                // fetch the next leaf, next time
                self.start_leaf = None;
            }
            Some((ss, position))
        } else {
            None
        }
    }
}

impl<'a, const WIDTH: usize> DoubleEndedIterator for SegmentIterator<'a, WIDTH> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.start_position >= self.end_position { return None; }
        if self.end_leaf.is_none() {
            if let Some((leaf, index, start_position)) = self.segment.find_string_segment(self.end_position - 1) {
                self.end_leaf = Some(leaf);
                self.end_index = index;
                let len = leaf.segment.span[self.end_index].as_ref().map_or(0, |ss| ss.char_length);
                self.end_position = start_position + len;
            } else {
                return None;
            }
        }

        let leaf = self.end_leaf.unwrap();
        if let Some(ss) = leaf.segment.span[self.end_index].as_ref() {
            self.end_position -= ss.char_length;
            if self.end_index > 0 {
                self.end_index -= 1;
            } else {
                // fetch the next leaf, next time
                self.end_leaf = None;
            }
            Some((ss, self.end_position))
        } else {
            None
        }
    }
}


// iterate string segments (or sections of them) across a char range
pub struct SegmentStringIterator<'a, const WIDTH: usize> {
    segment_iter: SegmentIterator<'a, WIDTH>,
    char_start: usize,
    char_end: usize,
}

impl<'a, const WIDTH: usize> Iterator for SegmentStringIterator<'a, WIDTH> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        if self.char_start >= self.char_end { return None; }

        // next string?
        self.segment_iter.next().map(|(ss, position)| {
            let start = self.char_start - position;
            let end = (self.char_end - position).min(ss.char_length);
            self.char_start = position + ss.char_length;
            ss.substr(start, end)
        })
    }
}

impl<'a, const WIDTH: usize> DoubleEndedIterator for SegmentStringIterator<'a, WIDTH> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.char_start >= self.char_end { return None; }

        // next string?
        self.segment_iter.next_back().map(|(ss, position)| {
            let start = position.max(self.char_start) - position;
            let end = (self.char_end - position).min(ss.char_length);
            self.char_end = position;
            ss.substr(start, end)
        })
    }
}


#[cfg(test)]
mod test {
    use unicode_segmentation::UnicodeSegmentation;
    use super::*;
    use crate::string::split_chars_at;


    // absurdly small segments to test chunking
    fn make_string(s: &str) -> Segment::<4> {
        let mut start = 0;
        let mut ret = Segment::Leaf(LeafSegment::default());

        while start < s.len() {
            let (bytes, _chars) = split_chars_at(&s[start..], 4);
            ret = ret.with_append_segment(StringSegment::new(&s[start .. start + bytes]));
            start += bytes;
        }
        ret
    }


    // make sure we can find a leaf by byte or char
    #[test]
    fn find_leaf() {
        let long_string = "abcdefghijklmnopqrstuvwxyz-:ABCDEFGHIJKLMNOPQRSTUVWXYZ_!/0123456789*@.";
        let segment = make_string(long_string);
        let x = segment.find_leaf(0, 0);
        assert!(x.is_some());
        assert_eq!(x.unwrap().1, 0);
        assert_eq!(format!("{:?}", x.unwrap().0), "LeafSegment { segment: (16:16)[ (4:4)\"abcd\", (4:4)\"efgh\", (4:4)\"ijkl\", (4:4)\"mnop\" ] }");

        let x = segment.find_leaf(19, 0);
        assert!(x.is_some());
        assert_eq!(x.unwrap().1, 16);
        assert_eq!(format!("{:?}", x.unwrap().0), "LeafSegment { segment: (16:16)[ (4:4)\"qrst\", (4:4)\"uvwx\", (4:4)\"yz-:\", (4:4)\"ABCD\" ] }");

        let x = segment.find_leaf(31, 0);
        assert!(x.is_some());
        assert_eq!(x.unwrap().1, 16);
        assert_eq!(format!("{:?}", x.unwrap().0), "LeafSegment { segment: (16:16)[ (4:4)\"qrst\", (4:4)\"uvwx\", (4:4)\"yz-:\", (4:4)\"ABCD\" ] }");

        let x = segment.find_leaf(32, 0);
        assert!(x.is_some());
        assert_eq!(x.unwrap().1, 32);
        assert_eq!(format!("{:?}", x.unwrap().0), "LeafSegment { segment: (16:16)[ (4:4)\"EFGH\", (4:4)\"IJKL\", (4:4)\"MNOP\", (4:4)\"QRST\" ] }");

        let x = segment.find_leaf(66, 0);
        assert!(x.is_some());
        assert_eq!(x.unwrap().1, 64);
        assert_eq!(format!("{:?}", x.unwrap().0), "LeafSegment { segment: (6:6)[ (4:4)\"789*\", (2:2)\"@.\" ] }");

        let x = segment.find_leaf(70, 0);
        assert!(x.is_none());

        let wacky_string = "te\u{301}po\u{308}ba\u{301}vi\u{308}ku\u{301}ce\u{308}";
        let segment = make_string(wacky_string);
        let x = segment.find_leaf(0, 0);
        assert!(x.is_some());
        assert_eq!(x.unwrap().1, 0);
        assert_eq!(format!("{:?}", x.unwrap().0), "LeafSegment { segment: (16:8)[ (4:2)\"te\\u{301}\", (4:2)\"po\\u{308}\", (4:2)\"ba\\u{301}\", (4:2)\"vi\\u{308}\" ] }");

        let x = segment.find_leaf(7, 0);
        assert!(x.is_some());
        assert_eq!(x.unwrap().1, 0);
        assert_eq!(format!("{:?}", x.unwrap().0), "LeafSegment { segment: (16:8)[ (4:2)\"te\\u{301}\", (4:2)\"po\\u{308}\", (4:2)\"ba\\u{301}\", (4:2)\"vi\\u{308}\" ] }");

        let x = segment.find_leaf(8, 0);
        assert!(x.is_some());
        assert_eq!(x.unwrap().1, 8);
        assert_eq!(format!("{:?}", x.unwrap().0), "LeafSegment { segment: (8:4)[ (4:2)\"ku\\u{301}\", (4:2)\"ce\\u{308}\" ] }");
    }

    #[test]
    fn iter_segments() {
        let long_string = "abcdefghijklmnopqrstuvwxyz-:ABCDEFGHIJKLMNOPQRSTUVWXYZ_!/0123456789*@.";
        let segment = make_string(long_string);
        let iter = SegmentIterator::spanning(&segment, 0, segment.char_len());
        assert_eq!(
            &iter.map(|(ss, _pos)| ss.str()).collect::<Vec<_>>().join(""),
            "abcdefghijklmnopqrstuvwxyz-:ABCDEFGHIJKLMNOPQRSTUVWXYZ_!/0123456789*@."
        );

        let mut iter = SegmentIterator::spanning(&segment, 10, segment.char_len());
        let first = iter.next();
        assert!(first.is_some());
        let (ss, pos) = first.unwrap();
        assert_eq!(pos, 8);
        assert_eq!(ss.str(), "ijkl");
        assert_eq!(
            &iter.map(|(ss, _pos)| ss.str()).collect::<Vec<_>>().join(""),
            "mnopqrstuvwxyz-:ABCDEFGHIJKLMNOPQRSTUVWXYZ_!/0123456789*@."
        );

        let mut iter = SegmentIterator::spanning(&segment, 17, segment.char_len());
        let first = iter.next();
        assert!(first.is_some());
        let (ss, pos) = first.unwrap();
        assert_eq!(pos, 16);
        assert_eq!(ss.str(), "qrst");
        assert_eq!(
            &iter.map(|(ss, _pos)| ss.str()).collect::<Vec<_>>().join(""),
            "uvwxyz-:ABCDEFGHIJKLMNOPQRSTUVWXYZ_!/0123456789*@."
        );

        let mut iter = SegmentIterator::spanning(&segment, 14, 21);
        let first = iter.next();
        assert!(first.is_some());
        let (ss, pos) = first.unwrap();
        assert_eq!(pos, 12);
        assert_eq!(ss.str(), "mnop");
        assert_eq!(
            &iter.map(|(ss, _pos)| ss.str()).collect::<Vec<_>>().join(""),
            "qrstuvwx"
        );

        let mut iter = SegmentIterator::spanning(&segment, 9, 21).rev();
        let first = iter.next();
        assert!(first.is_some());
        let (ss, pos) = first.unwrap();
        assert_eq!(pos, 20);
        assert_eq!(ss.str(), "uvwx");
        assert_eq!(
            &iter.map(|(ss, _pos)| ss.str()).collect::<Vec<_>>().join(""),
            "qrstmnopijkl"
        );
    }

    #[test]
    fn iter_strings() {
        let long_string = "abcdefghijklmnopqrstuvwxyz-:ABCDEFGHIJKLMNOPQRSTUVWXYZ_!/0123456789*@.";
        let segment = make_string(long_string);
        for start in 0..(long_string.len()) {
            for end in start..(long_string.len()) {
                let middle = segment.iter_strings(start, end).collect::<Vec<_>>().join("");
                assert_eq!(middle, &long_string[start..end]);
            }
        }

        let wacky_string = "te\u{301}po\u{308}ba\u{301}vi\u{308}ku\u{301}ce\u{308}";
        let segment = make_string(wacky_string);
        assert_eq!(segment.char_len(), 12);
        for start in 0..(segment.char_len()) {
            for end in start..(segment.char_len()) {
                let middle = segment.iter_strings(start, end).collect::<Vec<_>>().join("");
                let computed = wacky_string.graphemes(true).skip(start).take(end.saturating_sub(start))
                    .collect::<Vec<_>>().join("");
                assert_eq!(middle, computed);
            }
        }

        // reverse!

        trait Reversed {
            fn reversed(&self) -> String;
        }
        impl Reversed for str {
            fn reversed(&self) -> String { self.chars().rev().collect::<String>() }
        }

        // if we iter_strings in reverse, and reverse each string segment as
        // we go, it should be the same as reversing the whole string.
        let segment = make_string(long_string);
        for start in 0..(long_string.len()) {
            for end in start..(long_string.len()) {
                let middle = segment.iter_strings(start, end).rev().map(|s| s.reversed()).collect::<Vec<_>>().join("");
                assert_eq!(middle, long_string[start..end].reversed());
            }
        }
    }

    #[test]
    fn segment_get() {
        let wacky_string = "te\u{301}po\u{308}ba\u{301}vi\u{308}ku\u{301}ce\u{308}";
        let segment = make_string(wacky_string);
        assert_eq!(segment.char_len(), 12);
        for i in 0..(segment.char_len()) {
            assert_eq!(segment.get(i).unwrap(), wacky_string.graphemes(true).nth(i).unwrap());
        }
    }

    #[test]
    fn append_in_place() {
        let long_string = "abcdefghijklmnopqrstuvwxyz-:ABCDEFGHIJKLMNOPQRSTUVWXYZ_!/0123456789*@.";
        let segment = make_string(long_string);
        assert_eq!(segment.char_len(), 70);

        let mut s1 = segment.clone();
        assert_eq!(s1.append_in_place("%", 4), (1, 1));
        assert_eq!(
            format!("{s1:?}"),
            "(71:71)[ \
                (64:64)[ \
                    (16:16)[ (4:4)\"abcd\", (4:4)\"efgh\", (4:4)\"ijkl\", (4:4)\"mnop\" ], \
                    (16:16)[ (4:4)\"qrst\", (4:4)\"uvwx\", (4:4)\"yz-:\", (4:4)\"ABCD\" ], \
                    (16:16)[ (4:4)\"EFGH\", (4:4)\"IJKL\", (4:4)\"MNOP\", (4:4)\"QRST\" ], \
                    (16:16)[ (4:4)\"UVWX\", (4:4)\"YZ_!\", (4:4)\"/012\", (4:4)\"3456\" ] \
                ], \
                (7:7)[ \
                    (7:7)[ (4:4)\"789*\", (3:3)\"@.%\" ] \
                ] \
            ]"
        );

        let mut s1 = segment.clone();
        assert_eq!(s1.append_in_place("%&", 4), (2, 2));
        assert_eq!(
            format!("{s1:?}"),
            "(72:72)[ \
                (64:64)[ \
                    (16:16)[ (4:4)\"abcd\", (4:4)\"efgh\", (4:4)\"ijkl\", (4:4)\"mnop\" ], \
                    (16:16)[ (4:4)\"qrst\", (4:4)\"uvwx\", (4:4)\"yz-:\", (4:4)\"ABCD\" ], \
                    (16:16)[ (4:4)\"EFGH\", (4:4)\"IJKL\", (4:4)\"MNOP\", (4:4)\"QRST\" ], \
                    (16:16)[ (4:4)\"UVWX\", (4:4)\"YZ_!\", (4:4)\"/012\", (4:4)\"3456\" ] \
                ], \
                (8:8)[ \
                    (8:8)[ (4:4)\"789*\", (4:4)\"@.%&\" ] \
                ] \
            ]"
        );

        let mut s1 = segment.clone();
        assert_eq!(s1.append_in_place("%&?", 4), (2, 2));
        assert_eq!(
            format!("{s1:?}"),
            "(72:72)[ \
                (64:64)[ \
                    (16:16)[ (4:4)\"abcd\", (4:4)\"efgh\", (4:4)\"ijkl\", (4:4)\"mnop\" ], \
                    (16:16)[ (4:4)\"qrst\", (4:4)\"uvwx\", (4:4)\"yz-:\", (4:4)\"ABCD\" ], \
                    (16:16)[ (4:4)\"EFGH\", (4:4)\"IJKL\", (4:4)\"MNOP\", (4:4)\"QRST\" ], \
                    (16:16)[ (4:4)\"UVWX\", (4:4)\"YZ_!\", (4:4)\"/012\", (4:4)\"3456\" ] \
                ], \
                (8:8)[ \
                    (8:8)[ (4:4)\"789*\", (4:4)\"@.%&\" ] \
                ] \
            ]"
        );
    }
}