Skip to content

Commit 5572023

Browse files
committed
auto merge of #7162 : thestinger/rust/iterator, r=brson
2 parents b9119ed + 79cd2db commit 5572023

File tree

1 file changed

+47
-3
lines changed

1 file changed

+47
-3
lines changed

src/libstd/iterator.rs

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,12 @@ pub trait IteratorUtil<A> {
308308
/// assert!(!it.any_(|&x| *x == 3));
309309
/// ~~~
310310
fn any_(&mut self, f: &fn(A) -> bool) -> bool;
311+
312+
/// Return the first element satisfying the specified predicate
313+
fn find_(&mut self, predicate: &fn(&A) -> bool) -> Option<A>;
314+
315+
/// Return the index of the first element satisfying the specified predicate
316+
fn position_(&mut self, predicate: &fn(A) -> bool) -> Option<uint>;
311317
}
312318

313319
/// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also
@@ -421,7 +427,7 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
421427
None => { break; }
422428
}
423429
}
424-
return accum;
430+
accum
425431
}
426432

427433
/// Count the number of items yielded by an iterator
@@ -431,13 +437,35 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
431437
#[inline(always)]
432438
fn all(&mut self, f: &fn(A) -> bool) -> bool {
433439
for self.advance |x| { if !f(x) { return false; } }
434-
return true;
440+
true
435441
}
436442

437443
#[inline(always)]
438444
fn any_(&mut self, f: &fn(A) -> bool) -> bool {
439445
for self.advance |x| { if f(x) { return true; } }
440-
return false;
446+
false
447+
}
448+
449+
/// Return the first element satisfying the specified predicate
450+
#[inline(always)]
451+
fn find_(&mut self, predicate: &fn(&A) -> bool) -> Option<A> {
452+
for self.advance |x| {
453+
if predicate(&x) { return Some(x) }
454+
}
455+
None
456+
}
457+
458+
/// Return the index of the first element satisfying the specified predicate
459+
#[inline]
460+
fn position_(&mut self, predicate: &fn(A) -> bool) -> Option<uint> {
461+
let mut i = 0;
462+
for self.advance |x| {
463+
if predicate(x) {
464+
return Some(i);
465+
}
466+
i += 1;
467+
}
468+
None
441469
}
442470
}
443471

@@ -1055,4 +1083,20 @@ mod tests {
10551083
assert!(!v.iter().any_(|&x| x > 100));
10561084
assert!(!v.slice(0, 0).iter().any_(|_| fail!()));
10571085
}
1086+
1087+
#[test]
1088+
fn test_find() {
1089+
let v = &[1, 3, 9, 27, 103, 14, 11];
1090+
assert_eq!(*v.iter().find_(|x| *x & 1 == 0).unwrap(), 14);
1091+
assert_eq!(*v.iter().find_(|x| *x % 3 == 0).unwrap(), 3);
1092+
assert!(v.iter().find_(|x| *x % 12 == 0).is_none());
1093+
}
1094+
1095+
#[test]
1096+
fn test_position() {
1097+
let v = &[1, 3, 9, 27, 103, 14, 11];
1098+
assert_eq!(v.iter().position_(|x| *x & 1 == 0).unwrap(), 5);
1099+
assert_eq!(v.iter().position_(|x| *x % 3 == 0).unwrap(), 1);
1100+
assert!(v.iter().position_(|x| *x % 12 == 0).is_none());
1101+
}
10581102
}

0 commit comments

Comments
 (0)