Skip to content

Commit fcb474b

Browse files
alistaircarscaddenStephan Dilly
authored andcommitted
use is_char_boundary() to simplify logic
1 parent 8c4d52d commit fcb474b

File tree

1 file changed

+15
-19
lines changed

1 file changed

+15
-19
lines changed

src/components/textinput.rs

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -63,39 +63,35 @@ impl TextInputComponent {
6363

6464
/// Move the cursor left one char.
6565
fn decr_cursor(&mut self) {
66-
let mut new_pos: usize = 0;
67-
for (bytes, _) in self.msg.char_indices() {
68-
if bytes >= self.cursor_position {
69-
break;
70-
}
71-
new_pos = bytes;
66+
let mut index = self.cursor_position.saturating_sub(1);
67+
while index > 0 && !self.msg.is_char_boundary(index) {
68+
index -= 1;
7269
}
73-
self.cursor_position = new_pos;
70+
self.cursor_position = index;
7471
}
7572

7673
/// Get the position of the next char, or, if the cursor points
7774
/// to the last char, the `msg.len()`.
7875
/// Returns None when the cursor is already at `msg.len()`.
7976
fn next_char_position(&self) -> Option<usize> {
80-
let mut char_indices =
81-
self.msg[self.cursor_position..].char_indices();
82-
if char_indices.next().is_some() {
83-
if let Some((bytes, _)) = char_indices.next() {
84-
Some(self.cursor_position + bytes)
85-
} else {
86-
Some(self.msg.len())
87-
}
88-
} else {
89-
None
77+
if self.cursor_position >= self.msg.len() {
78+
return None;
9079
}
80+
let mut index = self.cursor_position.saturating_add(1);
81+
while index < self.msg.len()
82+
&& !self.msg.is_char_boundary(index)
83+
{
84+
index += 1;
85+
}
86+
Some(index)
9187
}
9288

93-
///
89+
/// Set the `msg`.
9490
pub fn set_text(&mut self, msg: String) {
9591
self.msg = msg;
9692
}
9793

98-
///
94+
/// Set the `title`.
9995
pub fn set_title(&mut self, t: String) {
10096
self.title = t;
10197
}

0 commit comments

Comments
 (0)