use alloc::fmt;
use alloc::string::{String, ToString};
use unicode_segmentation::{Graphemes, UnicodeSegmentation};
use crate::pascal_string::PascalString;
use crate::segment::{Segment, SegmentStringIterator};
use crate::string::split_chars_at;
use crate::{DEFAULT_MAX_SEGMENT, DEFAULT_WIDTH};
#[derive(Clone)]
pub struct SizedSegmentedString<const MAX_SEGMENT: usize = DEFAULT_MAX_SEGMENT, const WIDTH: usize = DEFAULT_WIDTH> {
root: Option<Segment<WIDTH>>,
}
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, self.root())
}
}
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> Default for SizedSegmentedString<MAX_SEGMENT, WIDTH> {
fn default() -> SizedSegmentedString<MAX_SEGMENT, WIDTH> {
SizedSegmentedString { root: Some(Segment::default()) }
}
}
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 root(&self) -> &Segment<WIDTH> {
self.root.as_ref().expect("always present")
}
fn root_mut(&mut self) -> &mut Segment<WIDTH> {
self.root.as_mut().expect("always present")
}
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 {
self.root().char_len() == 0
}
pub fn len(&self) -> usize {
self.root().len() as usize
}
pub fn char_len(&self) -> usize {
self.root().char_len() as usize
}
pub fn get(&self, char_offset: usize) -> Option<&str> {
self.root().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 {
self.root().substr_equals(char_start, char_end, other.root(), other_start, other_end)
}
pub fn substr_equals_str(&self, char_start: usize, char_end: usize, other: &str) -> bool {
self.root().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)
}
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))
}
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) -> SegmentStringIterator<'_, WIDTH> {
self.root().iter_strings(char_start, char_end)
}
fn append_str(&mut self, s: &str) {
let mut index = self.root_mut().append_in_place(s, MAX_SEGMENT).0;
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) {
let failed_string_segment = self.root_mut().append(PascalString::from(s));
if let Some(string_segment) = failed_string_segment {
let new_root = self.root.take().expect("always present").add_level();
self.root.replace(new_root);
assert!(self.root_mut().append(string_segment).is_none(), "contract violation!");
}
}
}
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())
}
}
pub struct CharIterator<'a, const WIDTH: usize> {
segment_iter: Option<SegmentStringIterator<'a, WIDTH>>,
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(|| {
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(|| {
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())
})
}
}