From fa70f3fd613da026fcf5aebb4868084aa0a32b94 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Wed, 10 Mar 2021 16:21:07 -0500 Subject: [PATCH] Optimize loopage of graphemes, finish chapter 5 --- src/row.rs | 86 ++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 54 insertions(+), 32 deletions(-) diff --git a/src/row.rs b/src/row.rs index 8661821..f9e46fb 100644 --- a/src/row.rs +++ b/src/row.rs @@ -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] {