Skip to content

Commit 50b0d0a

Browse files
committed
Specialize iterator for performance
Only nth could be optimized further, feel free to implement it :)
1 parent 567aadb commit 50b0d0a

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/btree_multiset.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ where
6666
iter: self.elem_counts.iter(),
6767
duplicate: None,
6868
duplicate_index: 0,
69+
len: self.size,
6970
_ghost: std::marker::PhantomData,
7071
}
7172
}

src/hash_multiset.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ where
6767
iter: self.elem_counts.iter(),
6868
duplicate: None,
6969
duplicate_index: 0,
70+
len: self.size,
7071
_ghost: std::marker::PhantomData,
7172
}
7273
}

src/iter.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ pub struct Iter<K: Clone, V: Borrow<usize>, InnerIter: Iterator<Item = (K, V)>>
1818
pub(crate) iter: InnerIter,
1919
pub(crate) duplicate: Option<<InnerIter as Iterator>::Item>,
2020
pub(crate) duplicate_index: usize,
21+
pub(crate) len: usize,
2122
pub(crate) _ghost: PhantomData<*const (K, V)>,
2223
}
2324

@@ -31,6 +32,7 @@ where
3132
iter: self.iter.clone(),
3233
duplicate: self.duplicate.clone(),
3334
duplicate_index: self.duplicate_index,
35+
len: self.len,
3436
_ghost: PhantomData,
3537
}
3638
}
@@ -52,9 +54,36 @@ impl<K: Clone, V: Borrow<usize>, InnerIter: Iterator<Item = (K, V)>> Iterator
5254
self.duplicate = None;
5355
self.duplicate_index = 0;
5456
}
57+
self.len -= 1;
5558
Some(key)
5659
} else {
5760
None
5861
}
5962
}
63+
64+
fn count(self) -> usize {
65+
self.len()
66+
}
67+
68+
fn fold<B, F>(self, init: B, mut f: F) -> B
69+
where
70+
F: FnMut(B, Self::Item) -> B,
71+
{
72+
self.iter.fold(init, |acc, (val, count)| {
73+
(0..*count.borrow()).fold(acc, |acc, _| f(acc, val.clone()))
74+
})
75+
}
76+
77+
fn size_hint(&self) -> (usize, Option<usize>) {
78+
let l = self.len();
79+
(l, Some(l))
80+
}
81+
}
82+
83+
impl<K: Clone, V: Borrow<usize>, InnerIter: Iterator<Item = (K, V)>> ExactSizeIterator
84+
for Iter<K, V, InnerIter>
85+
{
86+
fn len(&self) -> usize {
87+
self.len
88+
}
6089
}

0 commit comments

Comments
 (0)