Skip to content

Commit c967f2b

Browse files
committed
core: add a str iterator
1 parent d29ef7a commit c967f2b

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

src/libcore/str.rs

+56
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ use clone::Clone;
2424
use cmp::{TotalOrd, Ordering, Less, Equal, Greater};
2525
use libc;
2626
use option::{None, Option, Some};
27+
use iterator::Iterator;
2728
use ptr;
2829
use str;
2930
use u8;
@@ -2358,6 +2359,10 @@ pub trait StrSlice<'self> {
23582359
fn any(&self, it: &fn(char) -> bool) -> bool;
23592360
fn contains<'a>(&self, needle: &'a str) -> bool;
23602361
fn contains_char(&self, needle: char) -> bool;
2362+
#[cfg(stage1)]
2363+
#[cfg(stage2)]
2364+
#[cfg(stage3)]
2365+
fn char_iter(&self) -> StrCharIterator<'self>;
23612366
fn each(&self, it: &fn(u8) -> bool);
23622367
fn eachi(&self, it: &fn(uint, u8) -> bool);
23632368
fn each_reverse(&self, it: &fn(u8) -> bool);
@@ -2419,6 +2424,18 @@ impl<'self> StrSlice<'self> for &'self str {
24192424
fn contains_char(&self, needle: char) -> bool {
24202425
contains_char(*self, needle)
24212426
}
2427+
2428+
#[cfg(stage1)]
2429+
#[cfg(stage2)]
2430+
#[cfg(stage3)]
2431+
#[inline]
2432+
fn char_iter(&self) -> StrCharIterator<'self> {
2433+
StrCharIterator {
2434+
index: 0,
2435+
string: *self
2436+
}
2437+
}
2438+
24222439
/// Iterate over the bytes in a string
24232440
#[inline]
24242441
fn each(&self, it: &fn(u8) -> bool) { each(*self, it) }
@@ -2609,6 +2626,30 @@ impl Clone for ~str {
26092626
}
26102627
}
26112628
2629+
#[cfg(stage1)]
2630+
#[cfg(stage2)]
2631+
#[cfg(stage3)]
2632+
pub struct StrCharIterator<'self> {
2633+
priv index: uint,
2634+
priv string: &'self str,
2635+
}
2636+
2637+
#[cfg(stage1)]
2638+
#[cfg(stage2)]
2639+
#[cfg(stage3)]
2640+
impl<'self> Iterator<char> for StrCharIterator<'self> {
2641+
#[inline]
2642+
fn next(&mut self) -> Option<char> {
2643+
if self.index < self.string.len() {
2644+
let CharRange {ch, next} = char_range_at(self.string, self.index);
2645+
self.index = next;
2646+
Some(ch)
2647+
} else {
2648+
None
2649+
}
2650+
}
2651+
}
2652+
26122653
#[cfg(test)]
26132654
mod tests {
26142655
use char;
@@ -3901,4 +3942,19 @@ mod tests {
39013942
assert!(char_range_at_reverse("abc", 0).next == 0);
39023943
}
39033944
3945+
#[test]
3946+
fn test_iterator() {
3947+
use iterator::*;
3948+
let s = ~"ศไทย中华Việt Nam";
3949+
let v = ~['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
3950+
3951+
let mut pos = 0;
3952+
let mut it = s.char_iter();
3953+
3954+
for it.advance |c| {
3955+
assert_eq!(c, v[pos]);
3956+
pos += 1;
3957+
}
3958+
assert_eq!(pos, v.len());
3959+
}
39043960
}

0 commit comments

Comments
 (0)