Skip to content

Commit 0af64ae

Browse files
committed
Add a consume method to SmallIntMap
1 parent e388a80 commit 0af64ae

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

src/libextra/smallintmap.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,11 @@
1818

1919
use std::cmp;
2020
use std::container::{Container, Mutable, Map, Set};
21-
use std::iterator::{Iterator,IteratorUtil,ZipIterator,Counter};
21+
use std::iterator::*;
2222
use std::uint;
2323
use std::util::replace;
2424
use std::vec::{VecIterator,VecMutIterator,VecRevIterator,VecMutRevIterator};
25+
use std::vec::VecConsumeIterator;
2526

2627
#[allow(missing_doc)]
2728
pub struct SmallIntMap<T> {
@@ -204,6 +205,17 @@ impl<V> SmallIntMap<V> {
204205
iter: Counter::new(self.len() as int - 1, -1).zip(self.v.mut_rev_iter())
205206
}
206207
}
208+
209+
/// Empties the hash map, moving all values into the specified closure
210+
pub fn consume(&mut self)
211+
-> FilterMapIterator<(uint, Option<V>), (uint, V),
212+
EnumerateIterator<Option<V>, VecConsumeIterator<Option<V>>>>
213+
{
214+
let values = replace(&mut self.v, ~[]);
215+
values.consume_iter().enumerate().filter_map(|(i, v)| {
216+
v.map_consume(|v| (i, v))
217+
})
218+
}
207219
}
208220

209221
impl<V:Copy> SmallIntMap<V> {
@@ -625,6 +637,21 @@ mod tests {
625637

626638
assert!(a.iter().all(|(_,v)| *v == 5 ));
627639
}
640+
641+
#[test]
642+
fn test_consume() {
643+
let mut m = SmallIntMap::new();
644+
m.insert(1, ~2);
645+
let mut called = false;
646+
for m.consume().advance |(k, v)| {
647+
assert!(!called);
648+
called = true;
649+
assert_eq!(k, 1);
650+
assert_eq!(v, ~2);
651+
}
652+
assert!(called);
653+
m.insert(2, ~1);
654+
}
628655
}
629656

630657
#[cfg(test)]

0 commit comments

Comments
 (0)