Skip to content

Commit 8641c95

Browse files
committed
core: Add str::each_char
1 parent 9bff2f2 commit 8641c95

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Diff for: src/libcore/str.rs

+26
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ export
5555
all_between, any_between,
5656
map,
5757
each,
58+
each_char,
5859
bytes_iter,
5960
chars_iter,
6061
split_char_iter,
@@ -635,6 +636,18 @@ fn each(s: str, it: fn(u8) -> bool) {
635636
}
636637
}
637638

639+
#[doc = "Iterates over the chars in a string"]
640+
#[inline(always)]
641+
fn each_char(s: str, it: fn(char) -> bool) {
642+
let mut pos = 0u;
643+
let len = len(s);
644+
while pos < len {
645+
let {ch, next} = char_range_at(s, pos);
646+
pos = next;
647+
if !it(ch) { break; }
648+
}
649+
}
650+
638651
#[doc = "Iterate over the characters in a string"]
639652
fn chars_iter(s: str, it: fn(char)) {
640653
let mut pos = 0u;
@@ -2669,4 +2682,17 @@ mod tests {
26692682
assert to_utf16(from_utf16(u)) == u;
26702683
}
26712684
}
2685+
2686+
#[test]
2687+
fn test_each_char() {
2688+
let s = "abc";
2689+
let mut found_b = false;
2690+
for each_char(s) {|ch|
2691+
if ch == 'b' {
2692+
found_b = true;
2693+
break;
2694+
}
2695+
}
2696+
assert found_b;
2697+
}
26722698
}

0 commit comments

Comments
 (0)