Redo how index_before and index_after work

This commit is contained in:
Eryn Wells 2016-12-23 17:43:04 -07:00
parent fa2ff9e8ce
commit 4bd1d2c9c2

View file

@ -76,30 +76,44 @@ impl Lexable for char {
// //
pub trait RelativeIndexable { pub trait RelativeIndexable {
fn index_before(&self, &usize) -> Option<usize>; /// Get the index of the character boundary preceding the given index. The index does not need to be on a character
fn index_after(&self, &usize) -> Option<usize>; /// boundary.
fn index_before(&self, usize) -> usize;
/// Get the index of the character boundary following the given index. The index does not need to be on a character
/// boundary.
fn index_after(&self, usize) -> usize;
} }
impl RelativeIndexable for str { impl RelativeIndexable for str {
fn index_before(&self, index: &usize) -> Option<usize> { fn index_before(&self, index: usize) -> usize {
let mut prev_index = index - 1; if index == 0 {
if prev_index <= 0 { return 0;
return None;
} }
while !self.is_char_boundary(prev_index) { let mut index = index;
prev_index -= 1; if index > self.len() {
index = self.len();
} }
Some(prev_index) loop {
index -= 1;
if self.is_char_boundary(index) {
break;
}
}
index
} }
fn index_after(&self, index: &usize) -> Option<usize> { fn index_after(&self, index: usize) -> usize {
let mut next_index = index + 1; if index >= self.len() {
if next_index >= self.len() { return self.len();
return None;
} }
while !self.is_char_boundary(next_index) { let mut index = index;
next_index += 1; loop {
index += 1;
if self.is_char_boundary(index) {
break;
}
} }
Some(next_index) index
} }
} }