Skip to content

Commit

Permalink
Rollup merge of rust-lang#82585 - TrolledWoods:master, r=dtolnay
Browse files Browse the repository at this point in the history
Added CharIndices::offset function

The CharIndices iterator has a field internally called front_offset, that I think would be very useful to have access to.

You can already do something like ``char_indices.next().map(|(offset, _)| offset)``, but that is wordy, in addition to not handling the case where the iterator has ended, where you'd want the offset to be equal to the length.

I'm very new to the open source world and the rust repository, so I'm sorry if I missed a step or did something weird.
  • Loading branch information
Dylan-DPC authored Apr 22, 2021
2 parents 30f48d4 + fa1624c commit a6adb75
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions library/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@
#![feature(stmt_expr_attributes)]
#![feature(str_split_as_str)]
#![feature(str_split_inclusive_as_str)]
#![feature(char_indices_offset)]
#![feature(trait_alias)]
#![feature(transparent_unions)]
#![feature(try_blocks)]
Expand Down
24 changes: 24 additions & 0 deletions library/core/src/str/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,30 @@ impl<'a> CharIndices<'a> {
pub fn as_str(&self) -> &'a str {
self.iter.as_str()
}

/// Returns the byte position of the next character, or the length
/// of the underlying string if there are no more characters.
///
/// # Examples
///
/// ```
/// #![feature(char_indices_offset)]
/// let mut chars = "a楽".char_indices();
///
/// assert_eq!(chars.offset(), 0);
/// assert_eq!(chars.next(), Some((0, 'a')));
///
/// assert_eq!(chars.offset(), 1);
/// assert_eq!(chars.next(), Some((1, '楽')));
///
/// assert_eq!(chars.offset(), 4);
/// assert_eq!(chars.next(), None);
/// ```
#[inline]
#[unstable(feature = "char_indices_offset", issue = "83871")]
pub fn offset(&self) -> usize {
self.front_offset
}
}

/// An iterator over the bytes of a string slice.
Expand Down

0 comments on commit a6adb75

Please sign in to comment.