Skip to content

Commit 21bb7b8

Browse files
committed
Implement EscapeUnicode::nth
as a step from the appropriate state. Part of rust-lang#24214.
1 parent 1460667 commit 21bb7b8

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

src/libcore/char.rs

+17
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,23 @@ impl Iterator for EscapeUnicode {
446446
self.len()
447447
}
448448

449+
fn nth(&mut self, n: usize) -> Option<char> {
450+
let remaining = self.len().saturating_sub(n);
451+
452+
// hex_digit_idx = (number of hex digits still to be emitted) - 1
453+
// It can be computed from the remaining number of items by keeping
454+
// into account that:
455+
// - hex_digit_idx can never increase
456+
// - the last 2 items (last hex digit, '}') are not counted in hex_digit_idx
457+
let hex_digit_idx = ::cmp::min(self.hex_digit_idx, remaining.saturating_sub(2));
458+
459+
// state = number of items to be emitted for the state (as per state_len())
460+
// It can be computed because (remaining number of items) = state + hex_digit_idx
461+
let state = remaining - hex_digit_idx;
462+
463+
self.step(state, hex_digit_idx)
464+
}
465+
449466
fn last(self) -> Option<char> {
450467
match self.state {
451468
EscapeUnicodeState::Done => None,

0 commit comments

Comments
 (0)