From 8641c95221786d13c5e91f1d78c9d0158c376438 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Thu, 29 Mar 2012 22:28:26 -0700 Subject: [PATCH] core: Add str::each_char --- src/libcore/str.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 5d181930b93..2cf3f04fa94 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -55,6 +55,7 @@ export all_between, any_between, map, each, + each_char, bytes_iter, chars_iter, split_char_iter, @@ -635,6 +636,18 @@ fn each(s: str, it: fn(u8) -> bool) { } } +#[doc = "Iterates over the chars in a string"] +#[inline(always)] +fn each_char(s: str, it: fn(char) -> bool) { + let mut pos = 0u; + let len = len(s); + while pos < len { + let {ch, next} = char_range_at(s, pos); + pos = next; + if !it(ch) { break; } + } +} + #[doc = "Iterate over the characters in a string"] fn chars_iter(s: str, it: fn(char)) { let mut pos = 0u; @@ -2669,4 +2682,17 @@ mod tests { assert to_utf16(from_utf16(u)) == u; } } + + #[test] + fn test_each_char() { + let s = "abc"; + let mut found_b = false; + for each_char(s) {|ch| + if ch == 'b' { + found_b = true; + break; + } + } + assert found_b; + } }