Skip to content

Commit ea8a55b

Browse files
committed
iterator: make nth and last return Option
There isn't a way to take the length of any iterator, so failing on a zero length would make these much less useful.
1 parent a9c465c commit ea8a55b

File tree

1 file changed

+15
-35
lines changed

1 file changed

+15
-35
lines changed

src/libcore/iterator.rs

Lines changed: 15 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ pub trait IteratorUtil<A> {
4848
#[cfg(not(stage0))]
4949
fn advance(&mut self, f: &fn(A) -> bool) -> bool;
5050
fn to_vec(self) -> ~[A];
51-
fn nth(&mut self, n: uint) -> A;
52-
fn last(&mut self) -> A;
51+
fn nth(&mut self, n: uint) -> Option<A>;
52+
fn last(&mut self) -> Option<A>;
5353
fn fold<B>(&mut self, start: B, f: &fn(B, A) -> B) -> B;
5454
fn count(&mut self) -> uint;
5555
fn all(&mut self, f: &fn(&A) -> bool) -> bool;
@@ -154,30 +154,24 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
154154
return v;
155155
}
156156

157-
/// Get `n`th element of an iterator.
157+
/// Return the `n`th item yielded by an iterator.
158158
#[inline(always)]
159-
fn nth(&mut self, n: uint) -> A {
160-
let mut i = n;
159+
fn nth(&mut self, mut n: uint) -> Option<A> {
161160
loop {
162161
match self.next() {
163-
Some(x) => { if i == 0 { return x; }}
164-
None => { fail!("cannot get %uth element", n) }
162+
Some(x) => if n == 0 { return Some(x) },
163+
None => return None
165164
}
166-
i -= 1;
165+
n -= 1;
167166
}
168167
}
169168

170-
// Get last element of an iterator.
171-
//
172-
// If the iterator have an infinite length, this method won't return.
169+
/// Return the last item yielded by an iterator.
173170
#[inline(always)]
174-
fn last(&mut self) -> A {
175-
let mut elm = match self.next() {
176-
Some(x) => x,
177-
None => fail!("cannot get last element")
178-
};
179-
for self.advance |e| { elm = e; }
180-
return elm;
171+
fn last(&mut self) -> Option<A> {
172+
let mut last = None;
173+
for self.advance |x| { last = Some(x); }
174+
last
181175
}
182176

183177
/// Reduce an iterator to an accumulated value
@@ -679,29 +673,15 @@ mod tests {
679673
fn test_iterator_nth() {
680674
let v = &[0, 1, 2, 3, 4];
681675
for uint::range(0, v.len()) |i| {
682-
assert_eq!(v.iter().nth(i), &v[i]);
676+
assert_eq!(v.iter().nth(i).unwrap(), &v[i]);
683677
}
684678
}
685679

686-
#[test]
687-
#[should_fail]
688-
fn test_iterator_nth_fail() {
689-
let v = &[0, 1, 2, 3, 4];
690-
v.iter().nth(5);
691-
}
692-
693680
#[test]
694681
fn test_iterator_last() {
695682
let v = &[0, 1, 2, 3, 4];
696-
assert_eq!(v.iter().last(), &4);
697-
assert_eq!(v.slice(0, 1).iter().last(), &0);
698-
}
699-
700-
#[test]
701-
#[should_fail]
702-
fn test_iterator_last_fail() {
703-
let v: &[uint] = &[];
704-
v.iter().last();
683+
assert_eq!(v.iter().last().unwrap(), &4);
684+
assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0);
705685
}
706686

707687
#[test]

0 commit comments

Comments
 (0)