Skip to content

Commit b0d60a7

Browse files
committed
Add a way to iterate over a str's chars to std::str
1 parent 7080ac1 commit b0d60a7

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/lib/str.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export eq, lteq, hash, is_empty, is_not_empty, is_whitespace, byte_len, index,
1111
to_chars, char_len, char_at, bytes, is_ascii, shift_byte, pop_byte,
1212
unsafe_from_byte, unsafe_from_bytes, from_char, char_range_at,
1313
str_from_cstr, sbuf, as_buf, push_byte, utf8_char_width, safe_slice,
14-
contains;
14+
contains, chars;
1515

1616
native "c-stack-cdecl" mod rustrt {
1717
fn rust_str_push(&s: str, ch: u8);
@@ -299,6 +299,21 @@ Pluck a character out of a string
299299
*/
300300
fn char_at(s: str, i: uint) -> char { ret char_range_at(s, i).ch; }
301301

302+
/*
303+
Function: chars
304+
305+
Iterate over the characters in a string
306+
*/
307+
308+
fn chars(s: str, it: block(char)) {
309+
let pos = 0u, len = byte_len(s);
310+
while (pos < len) {
311+
let {ch, next} = char_range_at(s, pos);
312+
pos = next;
313+
it(ch);
314+
}
315+
}
316+
302317
/*
303318
Function: char_len
304319

src/test/stdtest/str.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,3 +315,16 @@ fn contains() {
315315
assert !str::contains("abcde", "def");
316316
assert !str::contains("", "a");
317317
}
318+
319+
#[test]
320+
fn chars() {
321+
let i = 0;
322+
str::chars("x\u03c0y") {|ch|
323+
alt i {
324+
0 { assert ch == 'x'; }
325+
1 { assert ch == '\u03c0'; }
326+
2 { assert ch == 'y'; }
327+
}
328+
i += 1;
329+
}
330+
}

0 commit comments

Comments
 (0)