CharAt trait, applied to str
This commit is contained in:
parent
fcb7a79721
commit
79080ff62b
1 changed files with 17 additions and 0 deletions
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue