Skip to content

Commit 02945f1

Browse files
committed
libcore: Add IteratoUtil::nth, first, last method
1 parent 9ffbe69 commit 02945f1

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

src/libcore/iterator.rs

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ pub trait IteratorUtil<A> {
4747
#[cfg(not(stage0))]
4848
fn advance(&mut self, f: &fn(A) -> bool) -> bool;
4949
fn to_vec(self) -> ~[A];
50+
fn nth(&mut self, n: uint) -> A;
51+
fn first(&mut self) -> A;
52+
fn last(&mut self) -> A;
5053
}
5154

5255
/// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also
@@ -146,6 +149,41 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
146149
for it.advance() |x| { v.push(x); }
147150
return v;
148151
}
152+
153+
/// Get `n`th element of an iterator.
154+
#[inline(always)]
155+
fn nth(&mut self, n: uint) -> A {
156+
let mut i = n;
157+
loop {
158+
match self.next() {
159+
Some(x) => { if i == 0 { return x; }}
160+
None => { fail!("cannot get %uth element", n) }
161+
}
162+
i -= 1;
163+
}
164+
}
165+
166+
// Get first elemet of an iterator.
167+
#[inline(always)]
168+
fn first(&mut self) -> A {
169+
match self.next() {
170+
Some(x) => x ,
171+
None => fail!("cannot get first element")
172+
}
173+
}
174+
175+
// Get last element of an iterator.
176+
//
177+
// If the iterator have an infinite length, this method won't return.
178+
#[inline(always)]
179+
fn last(&mut self) -> A {
180+
let mut elm = match self.next() {
181+
Some(x) => x,
182+
None => fail!("cannot get last element")
183+
};
184+
for self.advance |e| { elm = e; }
185+
return elm;
186+
}
149187
}
150188

151189
pub struct ChainIterator<T, U> {
@@ -567,4 +605,47 @@ mod tests {
567605
}
568606
assert_eq!(i, 10);
569607
}
608+
609+
#[test]
610+
fn test_iterator_nth() {
611+
let v = &[0, 1, 2, 3, 4];
612+
for uint::range(0, v.len()) |i| {
613+
assert_eq!(v.iter().nth(i), &v[i]);
614+
}
615+
}
616+
617+
#[test]
618+
#[should_fail]
619+
fn test_iterator_nth_fail() {
620+
let v = &[0, 1, 2, 3, 4];
621+
v.iter().nth(5);
622+
}
623+
624+
#[test]
625+
fn test_iterator_first() {
626+
let v = &[0, 1, 2, 3, 4];
627+
assert_eq!(v.iter().first(), &0);
628+
assert_eq!(v.slice(2, 5).iter().first(), &2);
629+
}
630+
631+
#[test]
632+
#[should_fail]
633+
fn test_iterator_first_fail() {
634+
let v: &[uint] = &[];
635+
v.iter().first();
636+
}
637+
638+
#[test]
639+
fn test_iterator_last() {
640+
let v = &[0, 1, 2, 3, 4];
641+
assert_eq!(v.iter().last(), &4);
642+
assert_eq!(v.slice(0, 1).iter().last(), &0);
643+
}
644+
645+
#[test]
646+
#[should_fail]
647+
fn test_iterator_last_fail() {
648+
let v: &[uint] = &[];
649+
v.iter().last();
650+
}
570651
}

0 commit comments

Comments
 (0)