Skip to content

Commit 55bb3a2

Browse files
committed
Add StreamingIteratorMut::map_deref_mut (h/t @arturoc)
1 parent 0b4d84d commit 55bb3a2

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

src/lib.rs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -586,6 +586,17 @@ pub trait StreamingIteratorMut: StreamingIterator {
586586
{
587587
self.fold_mut((), move |(), item| f(item));
588588
}
589+
590+
/// Creates a regular, non-streaming iterator which transforms mutable elements
591+
/// of this iterator by passing them to a closure.
592+
#[inline]
593+
fn map_deref_mut<B, F>(self, f: F) -> MapDerefMut<Self, F>
594+
where
595+
Self: Sized,
596+
F: FnMut(&mut Self::Item) -> B,
597+
{
598+
MapDerefMut { it: self, f }
599+
}
589600
}
590601

591602
impl<'a, I: ?Sized> StreamingIteratorMut for &'a mut I
@@ -1701,6 +1712,52 @@ where
17011712
}
17021713
}
17031714

1715+
/// A regular, non-streaming iterator which transforms the elements of a mutable streaming iterator.
1716+
#[derive(Debug)]
1717+
pub struct MapDerefMut<I, F> {
1718+
it: I,
1719+
f: F,
1720+
}
1721+
1722+
impl<I, B, F> Iterator for MapDerefMut<I, F>
1723+
where
1724+
I: StreamingIteratorMut,
1725+
F: FnMut(&mut I::Item) -> B,
1726+
{
1727+
type Item = B;
1728+
1729+
#[inline]
1730+
fn next(&mut self) -> Option<Self::Item> {
1731+
self.it.next_mut().map(&mut self.f)
1732+
}
1733+
1734+
#[inline]
1735+
fn size_hint(&self) -> (usize, Option<usize>) {
1736+
self.it.size_hint()
1737+
}
1738+
1739+
#[inline]
1740+
fn fold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
1741+
where
1742+
Self: Sized,
1743+
Fold: FnMut(Acc, Self::Item) -> Acc,
1744+
{
1745+
let mut map = self.f;
1746+
self.it.fold_mut(init, move |acc, item| f(acc, map(item)))
1747+
}
1748+
}
1749+
1750+
impl<I, B, F> DoubleEndedIterator for MapDerefMut<I, F>
1751+
where
1752+
I: DoubleEndedStreamingIteratorMut,
1753+
F: FnMut(&mut I::Item) -> B,
1754+
{
1755+
#[inline]
1756+
fn next_back(&mut self) -> Option<Self::Item> {
1757+
self.it.next_back_mut().map(&mut self.f)
1758+
}
1759+
}
1760+
17041761
/// A streaming iterator which transforms the elements of a streaming iterator.
17051762
#[derive(Debug)]
17061763
pub struct MapRef<I, F> {
@@ -2418,6 +2475,14 @@ mod test {
24182475
test_deref(it, &items);
24192476
}
24202477

2478+
#[test]
2479+
fn map_deref_mut() {
2480+
let mut items = [1, 2, 3];
2481+
let it = convert_mut(&mut items).map_deref_mut(|i| -core::mem::replace(i, 0));
2482+
test_deref(it, &[-1, -2, -3]);
2483+
assert_eq!(items, [0, 0, 0]);
2484+
}
2485+
24212486
#[test]
24222487
fn map_ref() {
24232488
#[derive(Clone)]

0 commit comments

Comments
 (0)