Optimize loopage of graphemes, finish chapter 5

This commit is contained in:
Timothy Warren 2021-03-10 16:21:07 -05:00
parent 297ff6b80b
commit fa70f3fd61

View File

@ -9,13 +9,10 @@ pub struct Row {
impl From<&str> for Row {
fn from(slice: &str) -> Self {
let mut row = Self {
Self {
string: String::from(slice),
len: 0,
};
row.update_len();
row
len: slice.graphemes(true).count(),
}
}
}
@ -50,55 +47,80 @@ impl Row {
self.len == 0
}
fn update_len(&mut self) {
self.len = self.string[..].graphemes(true).count();
}
pub fn insert(&mut self, at: usize, c: char) {
if at >= self.len() {
self.string.push(c);
} else {
let mut result: String = self.string[..].graphemes(true).take(at).collect();
let remainder: String = self.string[..].graphemes(true).skip(at).collect();
self.len += 1;
result.push(c);
result.push_str(&remainder);
self.string = result;
return;
}
self.update_len();
let mut result = String::new();
let mut length = 0;
for (index, grapheme) in self.string[..].graphemes(true).enumerate() {
length += 1;
if index == at {
length += 1;
result.push(c);
}
result.push_str(grapheme);
}
self.len = length;
self.string = result;
}
#[allow(clippy::integer_arithmetic)]
pub fn delete(&mut self, at: usize) {
if at >= self.len() {
return
} else {
let mut result: String = self.string[..].graphemes(true).take(at).collect();
let remainder: String = self.string[..].graphemes(true).skip(at + 1).collect();
result.push_str(&remainder);
self.string = result;
}
self.update_len();
let mut result = String::new();
let mut length = 0;
for (index, grapheme) in self.string[..].graphemes(true).enumerate() {
if index != at {
length += 1;
result.push_str(grapheme);
}
}
self.len = length;
self.string = result;
}
pub fn append(&mut self, new: &Self) {
self.string = format!("{}{}", self.string, new.string);
self.update_len();
self.len += new.len;
}
pub fn split(&mut self, at: usize) -> Self {
let beginning: String = self.string[..].graphemes(true).take(at).collect();
let remainder: String = self.string[..].graphemes(true).skip(at).collect();
let mut row = String::new();
let mut length = 0;
let mut splitted_row = String::new();
let mut splittend_length = 0;
self.string = beginning;
self.update_len();
for (index, grapheme) in self.string[..].graphemes(true).enumerate() {
if index < at {
length += 1;
row.push_str(grapheme);
} else {
splittend_length += 1;
splitted_row.push_str(grapheme);
}
}
Self::from(&remainder[..])
self.string = row;
self.len = length;
Self {
string: splitted_row,
len: splittend_length,
}
}
pub fn as_bytes(&self) -> &[u8] {