Skip to content

Commit 5b4986f

Browse files
committed
Auto merge of #29684 - stepancheg:size-hint, r=Gankro
* `size_hint()` cannot be relied upon to perform memory unsafe operations Same applies to `len()` function of `ExactSizeIterator` trait.
2 parents 9eb099d + f6f99ce commit 5b4986f

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/libcore/iter.rs

+23
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,25 @@ pub trait Iterator {
369369
/// `None` here means that either there is no known upper bound, or the
370370
/// upper bound is larger than `usize`.
371371
///
372+
/// # Implementation notes
373+
///
374+
/// It is not enforced that an iterator implementation yields the
375+
/// declared number of elements. A buggy iterator may yield less
376+
/// than the lower bound or more than the upper bound of elements.
377+
///
378+
/// `size_hint()` is primarily intended to be used for optimizations
379+
/// such as reserving space for the elements of the iterator, but
380+
/// must not be trusted to e.g. omit bounds checks in unsafe code.
381+
/// An incorrect implementation of `size_hint()` should not lead to
382+
/// memory safety violations.
383+
///
384+
/// That said, the implementation should provide a correct
385+
/// estimation, because otherwise it would be a violation of the
386+
/// trait's protocol.
387+
///
388+
/// The default implementation returns `(0, None)` which is correct
389+
/// for any iterator.
390+
///
372391
/// # Examples
373392
///
374393
/// Basic usage:
@@ -2731,7 +2750,11 @@ pub trait ExactSizeIterator: Iterator {
27312750
/// implementation, you can do so. See the [trait-level] docs for an
27322751
/// example.
27332752
///
2753+
/// This function has the same safety guarantees as [`size_hint()`]
2754+
/// function.
2755+
///
27342756
/// [trait-level]: trait.ExactSizeIterator.html
2757+
/// [`size_hint()`]: trait.Iterator.html#method.size_hint
27352758
///
27362759
/// # Examples
27372760
///

0 commit comments

Comments
 (0)