Skip to content

Commit f2bd441

Browse files
apasel422thestinger
authored andcommitted
std: Implement Iterator::size_hint method for Option iterators
1 parent a4af096 commit f2bd441

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/libstd/option.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,13 @@ impl<'self, A> Iterator<&'self A> for OptionIterator<'self, A> {
379379
fn next(&mut self) -> Option<&'self A> {
380380
util::replace(&mut self.opt, None)
381381
}
382+
383+
fn size_hint(&self) -> (uint, Option<uint>) {
384+
match self.opt {
385+
Some(_) => (1, Some(1)),
386+
None => (0, Some(0)),
387+
}
388+
}
382389
}
383390

384391
/// Mutable iterator over an `Option<A>`
@@ -390,6 +397,13 @@ impl<'self, A> Iterator<&'self mut A> for OptionMutIterator<'self, A> {
390397
fn next(&mut self) -> Option<&'self mut A> {
391398
util::replace(&mut self.opt, None)
392399
}
400+
401+
fn size_hint(&self) -> (uint, Option<uint>) {
402+
match self.opt {
403+
Some(_) => (1, Some(1)),
404+
None => (0, Some(0)),
405+
}
406+
}
393407
}
394408

395409
#[test]
@@ -487,3 +501,39 @@ fn test_filtered() {
487501
assert_eq!(some_stuff.get(), 42);
488502
assert!(modified_stuff.is_none());
489503
}
504+
505+
#[test]
506+
fn test_iter() {
507+
let val = 5;
508+
509+
let x = Some(val);
510+
let mut it = x.iter();
511+
512+
assert_eq!(it.size_hint(), (1, Some(1)));
513+
assert_eq!(it.next(), Some(&val));
514+
assert_eq!(it.size_hint(), (0, Some(0)));
515+
assert!(it.next().is_none());
516+
}
517+
518+
#[test]
519+
fn test_mut_iter() {
520+
let val = 5;
521+
let new_val = 11;
522+
523+
let mut x = Some(val);
524+
let mut it = x.mut_iter();
525+
526+
assert_eq!(it.size_hint(), (1, Some(1)));
527+
528+
match it.next() {
529+
Some(interior) => {
530+
assert_eq!(*interior, val);
531+
*interior = new_val;
532+
assert_eq!(x, Some(new_val));
533+
}
534+
None => assert!(false),
535+
}
536+
537+
assert_eq!(it.size_hint(), (0, Some(0)));
538+
assert!(it.next().is_none());
539+
}

0 commit comments

Comments
 (0)