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
use alloc::boxed::Box;
use alloc::fmt;
use alloc::string::ToString;
use unicode_segmentation::UnicodeSegmentation;


// treat a string as being made of grapheme clusters ("chars"), and slice using char indexes.
pub fn substr_graphemes(s: &str, char_start: usize, char_end: usize) -> &str {
    if char_start == char_end { return ""; }
    let mut iter = s.grapheme_indices(true).enumerate().filter_map(|(i, (b, _))|
        (i == char_start || i == char_start.max(char_end)).then_some(b)
    );
    let byte_start = iter.next().unwrap_or(s.len());
    let byte_end = iter.next().unwrap_or(s.len());
    &s[byte_start..byte_end]
}

// how many bytes (up to a limit) would fit in one string segment, splitting at grapheme-cluster boundaries?
// returns (bytes, chars)
pub fn split_chars_at(s: &str, limit: usize) -> (u32, u32) {
    if s.len() <= limit {
        (s.len() as u32, s.graphemes(true).count() as u32)
    } else {
        let iter = s.grapheme_indices(true).take_while(|(i, ss)| i + ss.len() <= limit);
        if let Some((ci, (i, ss))) = iter.enumerate().last() {
            ((i + ss.len()) as u32, ci as u32 + 1)
        } else {
            (0, 0)
        }
    }
}


#[derive(Clone, PartialEq, Eq)]
pub struct StringSegment {
    pub string: Box<str>,
    pub char_length: u32,  // in grapheme clusters
}

impl Default for StringSegment {
    fn default() -> StringSegment {
        StringSegment { string: "".into(), char_length: 0 }
    }
}

impl fmt::Debug for StringSegment {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}:{}){:?}", self.string.len(), self.char_length, self.string)
    }
}

impl StringSegment {
    pub fn new(s: &str) -> StringSegment {
        StringSegment { string: s.into(), char_length: s.graphemes(true).count() as u32 }
    }

    pub fn new_with_length(s: &str, char_length: u32) -> StringSegment {
        StringSegment { string: s.into(), char_length }
    }

    pub fn str(&self) -> &str {
        &self.string
    }

    pub fn get(&self, char_offset: usize) -> Option<&str> {
        self.str().graphemes(true).nth(char_offset)
    }

    pub fn substr(&self, char_start: usize, char_end: usize) -> &str {
        substr_graphemes(self.str(), char_start, char_end)
    }

    // add as much of `s` as will fit, and return how much was taken, in bytes and chars
    pub fn append_in_place(&mut self, s: &str, max_segment: usize) -> (u32, u32) {
        let count = max_segment - self.string.len();
        if count > 0 {
            let mut str = self.string.to_string();
            let (bytes, chars) = split_chars_at(s, count);
            str.push_str(&s[..bytes as usize]);
            self.string = str.into();
            self.char_length += chars;
            (bytes, chars)
        } else {
            (0, 0)
        }
    }
}


#[cfg(test)]
mod test {
    use super::*;


    #[test]
    fn split() {
        assert_eq!(split_chars_at("abc", 8), (3, 3));
        assert_eq!(split_chars_at("abcdefghijk", 8), (8, 8));
        assert_eq!(split_chars_at("\u{2048}\u{2048}\u{2048}\u{2048}", 8), (6, 2));

        let s = "\u{2048}\u{2048}\u{2042}\u{2030}";
        assert_eq!(s.len(), 12);
        assert_eq!(split_chars_at(s, 8), (6, 2));
        assert_eq!(&s[..6], "\u{2048}\u{2048}");
        assert_eq!(&s[6..], "\u{2042}\u{2030}");
    }
}