Skip to content

Commit 6ecd256

Browse files
authored
Rollup merge of rust-lang#82585 - TrolledWoods:master, r=dtolnay
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.
2 parents 37d4360 + fa1624c commit 6ecd256

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

library/core/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@
137137
#![feature(stmt_expr_attributes)]
138138
#![feature(str_split_as_str)]
139139
#![feature(str_split_inclusive_as_str)]
140+
#![feature(char_indices_offset)]
140141
#![feature(trait_alias)]
141142
#![feature(transparent_unions)]
142143
#![feature(try_blocks)]

library/core/src/str/iter.rs

+24
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,30 @@ impl<'a> CharIndices<'a> {
189189
pub fn as_str(&self) -> &'a str {
190190
self.iter.as_str()
191191
}
192+
193+
/// Returns the byte position of the next character, or the length
194+
/// of the underlying string if there are no more characters.
195+
///
196+
/// # Examples
197+
///
198+
/// ```
199+
/// #![feature(char_indices_offset)]
200+
/// let mut chars = "a楽".char_indices();
201+
///
202+
/// assert_eq!(chars.offset(), 0);
203+
/// assert_eq!(chars.next(), Some((0, 'a')));
204+
///
205+
/// assert_eq!(chars.offset(), 1);
206+
/// assert_eq!(chars.next(), Some((1, '楽')));
207+
///
208+
/// assert_eq!(chars.offset(), 4);
209+
/// assert_eq!(chars.next(), None);
210+
/// ```
211+
#[inline]
212+
#[unstable(feature = "char_indices_offset", issue = "83871")]
213+
pub fn offset(&self) -> usize {
214+
self.front_offset
215+
}
192216
}
193217

194218
/// An iterator over the bytes of a string slice.

0 commit comments

Comments
 (0)