Skip to content

Adds a OrderMap::drain() method #27

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 2 commits into from
Apr 29, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
target
Cargo.lock
26 changes: 26 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use std::hash::BuildHasher;
use std::hash::Hasher;
use std::collections::hash_map::RandomState;
use std::borrow::Borrow;
use std::ops::RangeFull;

use std::cmp::{max, Ordering};
use std::fmt;
Expand Down Expand Up @@ -979,6 +980,17 @@ impl<K, V, S> OrderMap<K, V, S>
self.entries.sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
self.into_iter()
}
/// Clears the `OrderMap`, returning all key-value pairs as a drain iterator.
/// Keeps the allocated memory for reuse.
pub fn drain(&mut self, range: RangeFull) -> Drain<K, V> {
for i in &mut self.indices {
*i = Pos::none();
}

Drain {
inner: self.entries.drain(range),
}
}
}

impl<K, V, S> OrderMap<K, V, S> {
Expand Down Expand Up @@ -1496,6 +1508,20 @@ impl<K, V, S> Eq for OrderMap<K, V, S>
{
}

pub struct Drain<'a, K, V> where K: 'a, V: 'a {
inner: ::std::vec::Drain<'a, Bucket<K, V>>
}

impl<'a, K, V> Iterator for Drain<'a, K, V> {
type Item = (K, V);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|bucket| (bucket.key, bucket.value))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
12 changes: 12 additions & 0 deletions tests/quick.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,18 @@ quickcheck! {
map.capacity() >= cap
}

fn drain(insert: Vec<u8>) -> bool {
let mut map = OrderMap::new();
for &key in &insert {
map.insert(key, ());
}
let mut clone = map.clone();
let drained = clone.drain(..);
for (key, _) in drained {
map.remove(&key);
}
map.is_empty()
}
}

use Op::*;
Expand Down