From a1210c9dae3ff7cf1d7afa08eadc76b4d7aaa7b9 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Fri, 10 Jul 2020 23:59:49 +0200 Subject: Improve safety of `Cursor::selection` --- native/src/widget/text_input/cursor.rs | 4 ++-- native/src/widget/text_input/editor.rs | 26 ++++++++++---------------- 2 files changed, 12 insertions(+), 18 deletions(-) (limited to 'native/src/widget/text_input') diff --git a/native/src/widget/text_input/cursor.rs b/native/src/widget/text_input/cursor.rs index 16e7a01b..aa03bb74 100644 --- a/native/src/widget/text_input/cursor.rs +++ b/native/src/widget/text_input/cursor.rs @@ -166,8 +166,8 @@ impl Cursor { end.min(value.len()) } - pub(crate) fn selection(&self) -> Option<(usize, usize)> { - match self.state { + pub(crate) fn selection(&self, value: &Value) -> Option<(usize, usize)> { + match self.state(value) { State::Selection { start, end } => { Some((start.min(end), start.max(end))) } diff --git a/native/src/widget/text_input/editor.rs b/native/src/widget/text_input/editor.rs index 5cda4f1d..b836f105 100644 --- a/native/src/widget/text_input/editor.rs +++ b/native/src/widget/text_input/editor.rs @@ -15,12 +15,10 @@ impl<'a> Editor<'a> { } pub fn insert(&mut self, character: char) { - match self.cursor.selection() { + match self.cursor.selection(self.value) { Some((left, right)) => { - if left < self.value.len() { - self.cursor.move_left(self.value); - self.value.remove_many(left, right.min(self.value.len())); - } + self.cursor.move_left(self.value); + self.value.remove_many(left, right.min(self.value.len())); } _ => (), } @@ -32,12 +30,10 @@ impl<'a> Editor<'a> { pub fn paste(&mut self, content: Value) { let length = content.len(); - match self.cursor.selection() { + match self.cursor.selection(self.value) { Some((left, right)) => { - if left < self.value.len() { - self.cursor.move_left(self.value); - self.value.remove_many(left, right.min(self.value.len())); - } + self.cursor.move_left(self.value); + self.value.remove_many(left, right.min(self.value.len())); } _ => (), } @@ -48,12 +44,10 @@ impl<'a> Editor<'a> { } pub fn backspace(&mut self) { - match self.cursor.selection() { + match self.cursor.selection(self.value) { Some((start, end)) => { - if start < self.value.len() { - self.cursor.move_left(self.value); - self.value.remove_many(start, end.min(self.value.len())); - } + self.cursor.move_left(self.value); + self.value.remove_many(start, end.min(self.value.len())); } None => { let start = self.cursor.start(self.value); @@ -67,7 +61,7 @@ impl<'a> Editor<'a> { } pub fn delete(&mut self) { - match self.cursor.selection() { + match self.cursor.selection(self.value) { Some(_) => { self.backspace(); } -- cgit