Skip to content

Commit ee9ce6b

Browse files
committed
Elide clone operation when calling iter::Cloned::advance_{back}_by()
This is a change in user-visible behavior.
1 parent f1ce0e6 commit ee9ce6b

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

library/core/src/iter/adapters/cloned.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ where
6060
self.it.map(T::clone).fold(init, f)
6161
}
6262

63+
#[inline]
64+
fn advance_by(&mut self, n: usize) -> Result<(), usize> {
65+
self.it.advance_by(n)
66+
}
67+
6368
#[doc(hidden)]
6469
unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> T
6570
where
@@ -96,6 +101,11 @@ where
96101
{
97102
self.it.map(T::clone).rfold(init, f)
98103
}
104+
105+
#[inline]
106+
fn advance_back_by(&mut self, n: usize) -> Result<(), usize> {
107+
self.it.advance_back_by(n)
108+
}
99109
}
100110

101111
#[stable(feature = "iter_cloned", since = "1.1.0")]

library/core/src/iter/traits/double_ended.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,8 +107,14 @@ pub trait DoubleEndedIterator: Iterator {
107107
/// outer iterator until it finds an inner iterator that is not empty, which then often
108108
/// allows it to return a more accurate `size_hint()` than in its initial state.
109109
///
110+
/// Implementations may elide side-effects such as calling closures or `clone` when they are
111+
/// not necessary to determine by how many steps an iterator can be advanced. For example
112+
/// [`Cloned::advance_back_by`] avoids unnecessary allocations by directly advancing its inner iterator
113+
/// instead.
114+
///
110115
/// [`advance_by`]: Iterator::advance_by
111116
/// [`Flatten`]: crate::iter::Flatten
117+
/// [`Cloned::advance_back_by`]: crate::iter::Cloned::advance_back_by
112118
/// [`next_back`]: DoubleEndedIterator::next_back
113119
///
114120
/// # Examples

library/core/src/iter/traits/iterator.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,13 @@ pub trait Iterator {
250250
/// can advance its outer iterator until it finds an inner iterator that is not empty, which
251251
/// then often allows it to return a more accurate `size_hint()` than in its initial state.
252252
///
253+
/// Implementations may elide side-effects such as calling closures or `clone` when they are
254+
/// not necessary to determine by how many steps an iterator can be advanced. For example
255+
/// [`Cloned::advance_by`] avoids unnecessary allocations by directly advancing its inner iterator
256+
/// instead.
257+
///
253258
/// [`Flatten`]: crate::iter::Flatten
259+
/// [`Cloned::advance_by`]: crate::iter::Cloned::advance_by
254260
/// [`next`]: Iterator::next
255261
///
256262
/// # Examples

0 commit comments

Comments
 (0)