Unify prefix_length and suffix_length signatures

This commit is contained in:
Alexandre Bury 2016-07-30 15:52:25 -07:00
parent d12622b56a
commit be7f2184e9
2 changed files with 23 additions and 21 deletions

View File

@ -34,9 +34,9 @@ pub use self::reader::ProgressReader;
/// prefix_length(my_text.graphemes(true), 5, "");
/// # }
/// ```
pub fn prefix_length<'a, I: Iterator<Item = &'a str>>(iter: I, width: usize,
delimiter: &str)
-> usize {
pub fn prefix_length<'a, I>(iter: I, width: usize, delimiter: &str) -> usize
where I: Iterator<Item = &'s str>
{
let delimiter_width = delimiter.width();
let delimiter_len = delimiter.len();
@ -64,19 +64,21 @@ pub fn prefix_length<'a, I: Iterator<Item = &'a str>>(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<Item = &'a str>
{
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, "")
}

View File

@ -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,7 +380,7 @@ 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],
simple_suffix_length(&self.content[self.offset..self.cursor],
available);
self.offset = self.cursor - suffix_length;
assert!(self.cursor >= self.offset);
@ -389,7 +389,7 @@ 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,
let suffix_length = simple_suffix_length(&self.content,
self.last_length - 1);
self.offset = self.content.len() - suffix_length;
}