From be7f2184e9edde93ebc9f70968e0591c5c07c596 Mon Sep 17 00:00:00 2001 From: Alexandre Bury Date: Sat, 30 Jul 2016 15:52:25 -0700 Subject: [PATCH] Unify prefix_length and suffix_length signatures --- src/utils/mod.rs | 34 ++++++++++++++++++---------------- src/views/edit_view.rs | 10 +++++----- 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 2718a2c..50d6a16 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -34,9 +34,9 @@ pub use self::reader::ProgressReader; /// prefix_length(my_text.graphemes(true), 5, ""); /// # } /// ``` -pub fn prefix_length<'a, I: Iterator>(iter: I, width: usize, - delimiter: &str) - -> usize { +pub fn prefix_length<'a, I>(iter: I, width: usize, delimiter: &str) -> usize + where I: Iterator +{ let delimiter_width = delimiter.width(); let delimiter_len = delimiter.len(); @@ -64,19 +64,21 @@ pub fn prefix_length<'a, I: Iterator>(iter: I, width: usize, /// Computes the length of a suffix that fits in the given `width`. /// +/// Doesn't break inside elements returned by `iter`. +/// /// Returns the number of bytes of the longest /// suffix from `text` that fits in `width`. -pub fn suffix_length(text: &str, width: usize) -> usize { - text.graphemes(true) - .rev() - .scan(0, |w, g| { - *w += g.width(); - if *w > width { - None - } else { - Some(g) - } - }) - .map(|g| g.len()) - .fold(0, |a, b| a + b) +/// +/// This is a shortcut for `prefix_length(iter.rev(), width, delimiter)` +pub fn suffix_length<'a, I>(iter: I, width: usize, delimiter: &str) -> usize + where I: DoubleEndedIterator +{ + prefix_length(iter.rev(), width, delimiter) +} + +/// Computes the length of a suffix that fits in the given `width`. +/// +/// Breaks between any two graphemes. +pub fn simple_suffix_length(text: &str, width: usize) -> usize { + suffix_length(text.graphemes(true), width, "") } diff --git a/src/views/edit_view.rs b/src/views/edit_view.rs index fba7408..5d46cf8 100644 --- a/src/views/edit_view.rs +++ b/src/views/edit_view.rs @@ -9,7 +9,7 @@ use theme::{ColorStyle, Effect}; use vec::Vec2; use view::View; use event::{Callback, Event, EventResult, Key}; -use utils::suffix_length; +use utils::simple_suffix_length; /// Input box where the user can enter and edit text. @@ -380,8 +380,8 @@ impl View for EditView { // From the end, count the length until we reach `available`. // Then sum the byte lengths. let suffix_length = - suffix_length(&self.content[self.offset..self.cursor], - available); + simple_suffix_length(&self.content[self.offset..self.cursor], + available); self.offset = self.cursor - suffix_length; assert!(self.cursor >= self.offset); @@ -389,8 +389,8 @@ impl View for EditView { // If we have too much space if self.content[self.offset..].width() < self.last_length { - let suffix_length = suffix_length(&self.content, - self.last_length - 1); + let suffix_length = simple_suffix_length(&self.content, + self.last_length - 1); self.offset = self.content.len() - suffix_length; }