CharAt trait, applied to str

This commit is contained in:
Eryn Wells 2016-12-23 17:44:44 -07:00
parent fcb7a79721
commit 79080ff62b

View file

@ -85,6 +85,12 @@ pub trait RelativeIndexable {
fn index_after(&self, usize) -> usize;
}
pub trait CharAt {
/// Get the character at the given byte index. This index must be at a character boundary as defined by
/// `is_char_boundary()`.
fn char_at(&self, usize) -> Option<char>;
}
impl RelativeIndexable for str {
fn index_before(&self, index: usize) -> usize {
if index == 0 {
@ -152,3 +158,14 @@ fn index_after_is_well_behaved_for_ascii() {
assert!(s.is_char_boundary(idx));
}
}
impl CharAt for str {
fn char_at(&self, index: usize) -> Option<char> {
if !self.is_char_boundary(index) {
return None;
}
let end = self.index_after(index);
let char_str = &self[index .. end];
char_str.chars().nth(0)
}
}