segmented_string 0.2.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
use alloc::boxed::Box;
use alloc::fmt;
use alloc::string::{String, ToString};
use core::mem;
use unicode_segmentation::{Graphemes, UnicodeSegmentation};

use crate::segment::{LeafSegment, Segment, SegmentStringIterator};
use crate::string::{StringSegment, split_chars_at, substr_graphemes};
use crate::{DEFAULT_MAX_SEGMENT, DEFAULT_WIDTH};


#[derive(Clone, Debug, PartialEq)]
enum Root<const WIDTH: usize> {
    String(Option<Box<str>>),
    Segment(Segment<WIDTH>),
}

impl<const WIDTH: usize> Default for Root<WIDTH> {
    fn default() -> Root<WIDTH> {
        Root::String(None)
    }
}


/// like clojure's "persistent vector", this is a vector stored as a b-tree
/// of segments. each leaf segment holds up to `MAX_SEGMENT` bytes of UTF-8
/// encoded characters that end on a grapheme-cluster boundary. each branch
/// segment holds up to `WIDTH` other segment pointers.
#[derive(Clone)]
pub struct SizedSegmentedString<const MAX_SEGMENT: usize = DEFAULT_MAX_SEGMENT, const WIDTH: usize = DEFAULT_WIDTH> {
    // head is filled in from the right, for easy prepend
    root: Root<WIDTH>,
}

impl<const MAX_SEGMENT: usize, const WIDTH: usize> Default for SizedSegmentedString<MAX_SEGMENT, WIDTH> {
    fn default() -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        SizedSegmentedString { root: Root::default() }
    }
}

impl<const MAX_SEGMENT: usize, const WIDTH: usize> fmt::Debug for SizedSegmentedString<MAX_SEGMENT, WIDTH> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "SegmentedString<{}, {}>", WIDTH, MAX_SEGMENT)?;
        match &self.root {
            Root::String(None) => write!(f, "(0:0)\"\""),
            Root::String(Some(s)) => write!(f, "({}:{}){:?}", s.len(), s.graphemes(true).count(), s),
            Root::Segment(segment) => write!(f, "{:?}", segment),
        }
    }
}

impl<const MAX_SEGMENT: usize, const WIDTH: usize> fmt::Display for SizedSegmentedString<MAX_SEGMENT, WIDTH> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for s in self.strings_in_range(0, self.char_len()) {
            write!(f, "{}", s)?;
        }
        Ok(())
    }
}

impl<const MAX_SEGMENT: usize, const WIDTH: usize> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
    pub fn empty() -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        SizedSegmentedString::default()
    }

    pub fn empty_with_segment_size<const M: usize>() -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        SizedSegmentedString::default()
    }

    fn from_str_iter<'a>(iter: impl IntoIterator<Item = &'a str>) -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        let mut ret = SizedSegmentedString::default();
        for s in iter { ret.append_segment(s); }
        ret
    }

    pub fn with_append<const M: usize, const W: usize>(
        mut self,
        other: &SizedSegmentedString<M, W>
    ) -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        for s in other.strings_in_range(0, other.char_len()) {
            self.append_str(s);
        }
        self
    }

    pub fn with_append_str(mut self, s: &str) -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        self.append_str(s);
        self
    }

    pub fn concat<'a, const M: usize, const W: usize>(
        strings: impl IntoIterator<Item = &'a SizedSegmentedString<M, W>>
    ) -> SizedSegmentedString<M, W> {
        let mut ret = SizedSegmentedString::default();
        for s in strings { ret.append(s); }
        ret
    }

    pub fn concat_str(strings: &[&str]) -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        let mut ret = SizedSegmentedString::default();
        for s in strings { ret.append_str(s); }
        ret
    }

    pub fn is_empty(&self) -> bool {
        match &self.root {
            Root::String(None) => true,
            Root::String(Some(s)) => s.is_empty(),
            Root::Segment(s) => s.char_len() == 0,
        }
    }

    /// length in *bytes* of UTF-8
    pub fn len(&self) -> usize {
        match &self.root {
            Root::String(None) => 0,
            Root::String(Some(s)) => s.len(),
            Root::Segment(s) => s.len() as usize,
        }
    }

    /// length in *grapheme clusters* (which we call "chars")
    pub fn char_len(&self) -> usize {
        match &self.root {
            Root::String(None) => 0,
            Root::String(Some(s)) => s.graphemes(true).count(),
            Root::Segment(s) => s.char_len() as usize,
        }
    }

    pub fn get(&self, char_offset: usize) -> Option<&str> {
        match &self.root {
            Root::String(None) => None,
            Root::String(Some(s)) => s.graphemes(true).nth(char_offset),
            Root::Segment(s) => s.get(char_offset),
        }
    }

    pub fn chars(&self) -> CharIterator<'_, WIDTH> {
        self.chars_range(0, self.char_len())
    }

    pub fn char_codes(&self) -> impl Iterator<Item = char> {
        self.chars().flat_map(|s| s.chars())
    }

    pub fn chars_range(&self, char_start: usize, char_end: usize) -> CharIterator<'_, WIDTH> {
        CharIterator {
            segment_iter: Some(self.strings_in_range(char_start, char_end)),
            grapheme_iter: None
        }
    }

    pub fn substr(&self, char_start: usize, char_end: usize) -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        SizedSegmentedString::from_str_iter(self.strings_in_range(char_start, char_end))
    }

    pub fn substr_equals<const M: usize, const W: usize>(
        &self,
        char_start: usize,
        char_end: usize,
        other: &SizedSegmentedString<M, W>,
        other_start: usize,
        other_end: usize
    ) -> bool {
        match &self.root {
            Root::String(None) => char_start == 0 && char_end == 0 && other_start == other_end,
            Root::String(Some(s)) => {
                other.substr_equals_str(other_start, other_end, substr_graphemes(s, char_start, char_end))
            },
            Root::Segment(s) => {
                match &other.root {
                    Root::String(None) => char_start == char_end,
                    Root::String(Some(s)) => {
                        self.substr_equals_str(char_start, char_end, substr_graphemes(s, other_start, other_end))
                    },
                    Root::Segment(os) => s.substr_equals(char_start, char_end, os, other_start, other_end),
                }
            }
        }
    }

    pub fn substr_equals_str(&self, char_start: usize, char_end: usize, other: &str) -> bool {
        match &self.root {
            Root::String(None) => other.is_empty(),
            Root::String(Some(s)) => substr_graphemes(s, char_start, char_end) == other,
            Root::Segment(s) => s.substr_equals_str(char_start, char_end, other),
        }
    }

    pub fn starts_with<const M: usize, const W: usize>(&self, other: &SizedSegmentedString<M, W>) -> bool {
        self.substr_equals(0, self.char_len().min(other.char_len()), other, 0, other.char_len())
    }

    pub fn ends_with<const M: usize, const W: usize>(&self, other: &SizedSegmentedString<M, W>) -> bool {
        let len = self.char_len().min(other.char_len());
        self.substr_equals(self.char_len() - len, self.char_len(), other, 0, other.char_len())
    }

    pub fn trim_left(&self) -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        let i = self.chars_range(0, self.char_len()).enumerate().find_map(|(i, s)|
            s.chars().any(|ch| !ch.is_whitespace() && ch != '\u{10}' && ch != '\u{13}').then_some(i)
        ).unwrap_or(self.char_len());
        self.substr(i, self.char_len())
    }

    pub fn trim_right(&self) -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        let i = self.chars_range(0, self.char_len()).rev().enumerate().find_map(|(i, s)| {
            let i = self.char_len() - i - 1;
            s.chars().any(|ch| !ch.is_whitespace() && ch != '\u{10}' && ch != '\u{13}').then_some(i + 1)
        }).unwrap_or(0);
        self.substr(0, i)
    }

    pub fn trim(&self) -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        let left = self.chars_range(0, self.char_len()).enumerate().find_map(|(i, s)|
            s.chars().any(|ch| !ch.is_whitespace() && ch != '\u{10}' && ch != '\u{13}').then_some(i)
        ).unwrap_or(self.char_len());
        let right = self.chars_range(0, self.char_len()).rev().enumerate().find_map(|(i, s)| {
            let i = self.char_len() - i - 1;
            s.chars().any(|ch| !ch.is_whitespace() && ch != '\u{10}' && ch != '\u{13}').then_some(i + 1)
        }).unwrap_or(0);
        self.substr(left, right)
    }

    /// try to find the left-most occurrence of `needle` in this string,
    /// starting at `from_index`. if found, returns the index it was found at.
    /// warning: this is not optimized! it just scans the string linearly,
    /// calling `substr_equals`.
    pub fn index_of<const M: usize, const W: usize>(
        &self,
        needle: &SizedSegmentedString<M, W>,
        from_index: usize
    ) -> Option<usize> {
        let len = needle.len();
        if len > self.len() { return None; }
        if from_index + len > self.len() { return None; }
        (from_index .. self.len() - len).find(|&i| self.substr_equals(i, i + len, needle, 0, len))
    }

    /// try to find the right-most occurrence of `needle` in this string,
    /// starting at `from_index`. if found, returns the index it was found at.
    /// warning: this is not optimized! it just scans the string linearly,
    /// calling `substr_equals`.
    pub fn reverse_index_of<const M: usize, const W: usize>(
        &self,
        needle: &SizedSegmentedString<M, W>,
        from_index: usize
    ) -> Option<usize> {
        let len = needle.len();
        if len > self.len() { return None; }
        (0 .. from_index.min(self.len() - len)).rfind(|&i| self.substr_equals(i, i + len, needle, 0, len))
    }

    fn append<const M: usize, const W: usize>(&mut self, other: &SizedSegmentedString<M, W>) {
        for s in other.strings_in_range(0, other.char_len()) {
            self.append_str(s);
        }
    }

    fn strings_in_range(&self, char_start: usize, char_end: usize) -> StringIterator<'_, WIDTH> {
        match &self.root {
            Root::String(str) => StringIterator::String { str: str.as_deref().unwrap_or(""), char_start, char_end },
            Root::Segment(s) => StringIterator::Segment(s.iter_strings(char_start, char_end)),
        }
    }

    fn append_str(&mut self, s: &str) {
        let mut index = 0;

        // first, finish off any incomplete segment
        match &mut self.root {
            Root::String(str) => {
                let remain = MAX_SEGMENT - str.as_ref().map(|str| str.len()).unwrap_or_default();
                if remain > 0 {
                    let (bytes, _) = split_chars_at(s, remain);
                    let mut builder = String::new();
                    if let Some(str) = str { builder.push_str(str); }
                    builder.push_str(&s[..bytes as usize]);
                    self.root = Root::String(Some(builder.into()));
                    index += bytes;
                }
            },
            Root::Segment(segment) => {
                index = segment.append_in_place(s, MAX_SEGMENT).0;
            }
        }

        // then turn the rest into new full segments
        while index < s.len() as u32 {
            let (bytes, _chars) = split_chars_at(&s[index as usize..], MAX_SEGMENT);
            self.append_segment(&s[index as usize .. (index + bytes) as usize]);
            index += bytes;
        }
    }

    fn append_segment(&mut self, s: &str) {
        // if the tree is full, our new string segment will be returned to us.
        let failed_string_segment = match &mut self.root {
            Root::String(None) => {
                self.root = Root::String(Some(s.into()));
                None
            },
            Root::String(Some(str)) => {
                // make it a leaf. tricksy swap to preserve the old string segment.
                let mut leaf = LeafSegment::from_str(str, str.graphemes(true).count() as u32);
                let mut old_root = Root::default();
                mem::swap(&mut old_root, &mut self.root);
                leaf.append(StringSegment::new(s));
                self.root = Root::Segment(Segment::Leaf(leaf));
                None
            },
            Root::Segment(segment) => {
                segment.append(StringSegment::new(s))
            },
        };

        if let Some(string_segment) = failed_string_segment {
            // branch full. add a level and try again.
            let mut old_root = Root::default();
            mem::swap(&mut old_root, &mut self.root);
            if let Root::Segment(old_segment) = old_root {
                self.root = Root::Segment(old_segment.add_level());
            }

            if let Root::Segment(s) = &mut self.root {
                assert!(s.append(string_segment).is_none(), "contract violation!");
            } else {
                panic!();  // impossible
            }
        }
    }
}

impl<const MAX_SEGMENT: usize, const WIDTH: usize> From<&str> for SizedSegmentedString<MAX_SEGMENT, WIDTH> {
    fn from(s: &str) -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        SizedSegmentedString::default().with_append_str(s)
    }
}

impl<const MAX_SEGMENT: usize, const WIDTH: usize> From<String> for SizedSegmentedString<MAX_SEGMENT, WIDTH> {
    fn from(s: String) -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        SizedSegmentedString::default().with_append_str(&s)
    }
}

impl<const MAX_SEGMENT: usize, const WIDTH: usize> From<&String> for SizedSegmentedString<MAX_SEGMENT, WIDTH> {
    fn from(s: &String) -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
        SizedSegmentedString::default().with_append_str(s)
    }
}

impl<const MAX_SEGMENT: usize, const WIDTH: usize> From<&SizedSegmentedString<MAX_SEGMENT, WIDTH>> for String {
    fn from(s: &SizedSegmentedString<MAX_SEGMENT, WIDTH>) -> String {
        s.to_string()
    }
}

impl<const MAX_SEGMENT: usize, const WIDTH: usize> PartialEq for SizedSegmentedString<MAX_SEGMENT, WIDTH> {
    fn eq(&self, other: &SizedSegmentedString<MAX_SEGMENT, WIDTH>) -> bool {
        self.substr_equals(0, self.char_len(), other, 0, other.char_len())
    }
}


// iterate chars (grapheme clusters) by walking the string segments and then the chars within them
pub struct CharIterator<'a, const WIDTH: usize> {
    // which string segment are we in:
    segment_iter: Option<StringIterator<'a, WIDTH>>,
    // which grapheme within that segment:
    grapheme_iter: Option<Graphemes<'a>>,
}

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

    fn next(&mut self) -> Option<Self::Item> {
        self.grapheme_iter.as_mut().and_then(|iter| iter.next()).or_else(|| {
            // next string?
            self.grapheme_iter = self.segment_iter.as_mut().and_then(|iter| iter.next()).map(|s| s.graphemes(true));
            self.grapheme_iter.as_mut().and_then(|iter| iter.next())
        })
    }
}

impl<'a, const WIDTH: usize> DoubleEndedIterator for CharIterator<'a, WIDTH> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.grapheme_iter.as_mut().and_then(|iter| iter.next_back()).or_else(|| {
            // next string?
            self.grapheme_iter = self.segment_iter.as_mut().and_then(|iter| iter.next_back()).map(|s| s.graphemes(true));
            self.grapheme_iter.as_mut().and_then(|iter| iter.next_back())
        })
    }
}


// iterate string segments
pub enum StringIterator<'a, const WIDTH: usize> {
    String { str: &'a str, char_start: usize, char_end: usize },
    Segment(SegmentStringIterator<'a, WIDTH>),
}

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

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            StringIterator::String { str, char_start, char_end } => {
                if char_end == char_start { return None; }
                let ret = substr_graphemes(str, *char_start, *char_end);
                *char_end = *char_start;
                Some(ret)
            },
            StringIterator::Segment(iter) => iter.next(),
        }
    }
}

impl<'a, const WIDTH: usize> DoubleEndedIterator for StringIterator<'a, WIDTH> {
    fn next_back(&mut self) -> Option<Self::Item> {
        match self {
            StringIterator::String { str, char_start, char_end } => {
                if char_end == char_start { return None; }
                let ret = substr_graphemes(str, *char_start, *char_end);
                *char_end = *char_start;
                Some(ret)
            },
            StringIterator::Segment(iter) => iter.next_back(),
        }
    }
}