segmented_string 0.3.0

an immutable string type built from array segments, similar to clojure's persistent vector, with unicode grapheme/width support
Documentation
use alloc::alloc::Layout;
use alloc::string::String;
use core::fmt;
use core::mem;
use core::ptr;
use core::slice;
use unicode_segmentation::UnicodeSegmentation;

use crate::string::split_chars_at;
use crate::string::substr_graphemes;


// offsets of byte-sized metadata in the buffer
const I_LEN: usize = 0;
const I_CHAR_LEN: usize = 1;
const I_DATA: usize = 2;


#[repr(transparent)]
pub struct PascalString {
    data: ptr::NonNull<u8>,
}

// very important to me that an Option<PascalString> is still 1 word in size.
// (vscode can't figure it out, but the rust compiler agrees.)
const _: () = assert!(mem::size_of::<Option<PascalString>>() == mem::size_of::<usize>());

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

impl PascalString {
    fn alloc(len: usize, char_len: usize, copy_from: *const u8, copy_from_len: usize) -> ptr::NonNull<u8> {
        assert!(len < 256);
        assert!(char_len < 256);
        let layout = Layout::from_size_align(len + I_DATA, 1).expect("alloc");
        unsafe {
            // can't import "alloc" because it's also the name of the module :/
            let data = alloc::alloc::alloc(layout);
            *(data.wrapping_add(I_LEN)) = len as u8;
            *(data.wrapping_add(I_CHAR_LEN)) = char_len as u8;
            data.wrapping_add(I_DATA).copy_from_nonoverlapping(copy_from, copy_from_len);
            ptr::NonNull::new_unchecked(data)
        }
    }

    #[inline]
    pub fn len(&self) -> usize {
        unsafe { *(self.data.as_ptr().wrapping_add(I_LEN)) as usize }
    }

    #[inline]
    pub fn char_len(&self) -> usize {
        unsafe { *(self.data.as_ptr().wrapping_add(I_CHAR_LEN)) as usize }
    }

    pub fn as_str(&self) -> &str {
        unsafe {
            str::from_utf8_unchecked(slice::from_raw_parts(self.data.as_ptr().wrapping_add(I_DATA), self.len()))
        }
    }

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

    pub fn substr(&self, char_start: usize, char_end: usize) -> &str {
        substr_graphemes(self.as_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) {
        assert!(max_segment < 256);
        let count = max_segment - self.len();
        if count > 0 {
            let (bytes, chars) = split_chars_at(s, count);
            let new_len = self.len() + bytes as usize;
            let new_char_len = self.char_len() + chars as usize;
            let old_layout = Layout::from_size_align(self.len() + I_DATA, 1).expect("dealloc");

            let p = self.data.as_ptr().wrapping_add(I_DATA);
            let new_data = PascalString::alloc(new_len, new_char_len, p, self.len());
            unsafe {
                // copy the 2nd half and dealloc the old one
                let dest = new_data.as_ptr().wrapping_add(self.len() + I_DATA);
                dest.copy_from_nonoverlapping(s.as_ptr(), bytes as usize);
                alloc::alloc::dealloc(self.data.as_ptr(), old_layout);
            }
            self.data = new_data;

            (bytes, chars)
        } else {
            (0, 0)
        }
    }

    pub fn take_from(s: &str, max_segment: usize) -> (PascalString, u32, u32) {
        let (bytes, chars) = split_chars_at(s, max_segment);
        let ps = PascalString::from(&s[..bytes as usize]);
        (ps, bytes, chars)
    }
}

impl From<&str> for PascalString {
    fn from(s: &str) -> PascalString {
        assert!(s.len() < 256);
        let data = PascalString::alloc(s.len(), s.graphemes(true).count(), s.as_ptr(), s.len());
        PascalString { data }
    }
}

impl From<String> for PascalString {
    fn from(s: String) -> PascalString {
        PascalString::from(s.as_str())
    }
}

impl Drop for PascalString {
    fn drop(&mut self) {
        unsafe {
            let layout = Layout::from_size_align(self.len() + I_DATA, 1).expect("dealloc");
            alloc::alloc::dealloc(self.data.as_ptr(), layout);
        }
    }
}

impl Clone for PascalString {
    fn clone(&self) -> PascalString {
        // alloc a new deep copy
        let p = self.data.as_ptr().wrapping_add(I_DATA);
        let data = PascalString::alloc(self.len(), self.char_len(), p, self.len());
        PascalString { data }
    }
}

impl PartialEq for PascalString {
    fn eq(&self, other: &PascalString) -> bool {
        self.as_str() == other.as_str()
    }
}