Skip to content

Commit 0096328

Browse files
authored
Merge pull request rust-lang#27 from stevej/master
Adds a OrderMap::drain() method
2 parents dc0be46 + 68db5d8 commit 0096328

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
target
2+
Cargo.lock

src/lib.rs

+26
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use std::hash::BuildHasher;
99
use std::hash::Hasher;
1010
use std::collections::hash_map::RandomState;
1111
use std::borrow::Borrow;
12+
use std::ops::RangeFull;
1213

1314
use std::cmp::{max, Ordering};
1415
use std::fmt;
@@ -979,6 +980,17 @@ impl<K, V, S> OrderMap<K, V, S>
979980
self.entries.sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
980981
self.into_iter()
981982
}
983+
/// Clears the `OrderMap`, returning all key-value pairs as a drain iterator.
984+
/// Keeps the allocated memory for reuse.
985+
pub fn drain(&mut self, range: RangeFull) -> Drain<K, V> {
986+
for i in &mut self.indices {
987+
*i = Pos::none();
988+
}
989+
990+
Drain {
991+
inner: self.entries.drain(range),
992+
}
993+
}
982994
}
983995

984996
impl<K, V, S> OrderMap<K, V, S> {
@@ -1496,6 +1508,20 @@ impl<K, V, S> Eq for OrderMap<K, V, S>
14961508
{
14971509
}
14981510

1511+
pub struct Drain<'a, K, V> where K: 'a, V: 'a {
1512+
inner: ::std::vec::Drain<'a, Bucket<K, V>>
1513+
}
1514+
1515+
impl<'a, K, V> Iterator for Drain<'a, K, V> {
1516+
type Item = (K, V);
1517+
fn next(&mut self) -> Option<Self::Item> {
1518+
self.inner.next().map(|bucket| (bucket.key, bucket.value))
1519+
}
1520+
fn size_hint(&self) -> (usize, Option<usize>) {
1521+
self.inner.size_hint()
1522+
}
1523+
}
1524+
14991525
#[cfg(test)]
15001526
mod tests {
15011527
use super::*;

tests/quick.rs

+12
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,18 @@ quickcheck! {
105105
map.capacity() >= cap
106106
}
107107

108+
fn drain(insert: Vec<u8>) -> bool {
109+
let mut map = OrderMap::new();
110+
for &key in &insert {
111+
map.insert(key, ());
112+
}
113+
let mut clone = map.clone();
114+
let drained = clone.drain(..);
115+
for (key, _) in drained {
116+
map.remove(&key);
117+
}
118+
map.is_empty()
119+
}
108120
}
109121

110122
use Op::*;

0 commit comments

Comments
 (0)