@@ -24,6 +24,7 @@ use clone::Clone;
24
24
use cmp:: { TotalOrd , Ordering , Less , Equal , Greater } ;
25
25
use libc;
26
26
use option:: { None , Option , Some } ;
27
+ use iterator:: Iterator ;
27
28
use ptr;
28
29
use str;
29
30
use u8;
@@ -2358,6 +2359,10 @@ pub trait StrSlice<'self> {
2358
2359
fn any(&self, it: &fn(char) -> bool) -> bool;
2359
2360
fn contains<'a>(&self, needle: &'a str) -> bool;
2360
2361
fn contains_char(&self, needle: char) -> bool;
2362
+ #[cfg(stage1)]
2363
+ #[cfg(stage2)]
2364
+ #[cfg(stage3)]
2365
+ fn char_iter(&self) -> StrCharIterator<'self>;
2361
2366
fn each(&self, it: &fn(u8) -> bool);
2362
2367
fn eachi(&self, it: &fn(uint, u8) -> bool);
2363
2368
fn each_reverse(&self, it: &fn(u8) -> bool);
@@ -2419,6 +2424,18 @@ impl<'self> StrSlice<'self> for &'self str {
2419
2424
fn contains_char(&self, needle: char) -> bool {
2420
2425
contains_char(*self, needle)
2421
2426
}
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
+
2422
2439
/// Iterate over the bytes in a string
2423
2440
#[inline]
2424
2441
fn each(&self, it: &fn(u8) -> bool) { each(*self, it) }
@@ -2609,6 +2626,30 @@ impl Clone for ~str {
2609
2626
}
2610
2627
}
2611
2628
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
+
2612
2653
#[cfg(test)]
2613
2654
mod tests {
2614
2655
use char;
@@ -3901,4 +3942,19 @@ mod tests {
3901
3942
assert!(char_range_at_reverse(" abc", 0).next == 0);
3902
3943
}
3903
3944
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
+ }
3904
3960
}
0 commit comments