]>
git.proxmox.com Git - rustc.git/blob - library/core/src/iter/traits/exact_size.rs
1 /// An iterator that knows its exact length.
3 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
4 /// If an iterator knows how many times it can iterate, providing access to
5 /// that information can be useful. For example, if you want to iterate
6 /// backwards, a good start is to know where the end is.
8 /// When implementing an `ExactSizeIterator`, you must also implement
9 /// [`Iterator`]. When doing so, the implementation of [`Iterator::size_hint`]
10 /// *must* return the exact size of the iterator.
12 /// The [`len`] method has a default implementation, so you usually shouldn't
13 /// implement it. However, you may be able to provide a more performant
14 /// implementation than the default, so overriding it in this case makes sense.
16 /// Note that this trait is a safe trait and as such does *not* and *cannot*
17 /// guarantee that the returned length is correct. This means that `unsafe`
18 /// code **must not** rely on the correctness of [`Iterator::size_hint`]. The
19 /// unstable and unsafe [`TrustedLen`](super::marker::TrustedLen) trait gives
20 /// this additional guarantee.
22 /// [`len`]: ExactSizeIterator::len
29 /// // a finite range knows exactly how many times it will iterate
32 /// assert_eq!(5, five.len());
35 /// In the [module-level docs], we implemented an [`Iterator`], `Counter`.
36 /// Let's implement `ExactSizeIterator` for it as well:
38 /// [module-level docs]: crate::iter
41 /// # struct Counter {
45 /// # fn new() -> Counter {
46 /// # Counter { count: 0 }
49 /// # impl Iterator for Counter {
50 /// # type Item = usize;
51 /// # fn next(&mut self) -> Option<Self::Item> {
52 /// # self.count += 1;
53 /// # if self.count < 6 {
54 /// # Some(self.count)
60 /// impl ExactSizeIterator for Counter {
61 /// // We can easily calculate the remaining number of iterations.
62 /// fn len(&self) -> usize {
67 /// // And now we can use it!
69 /// let counter = Counter::new();
71 /// assert_eq!(5, counter.len());
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub trait ExactSizeIterator
: Iterator
{
75 /// Returns the exact length of the iterator.
77 /// The implementation ensures that the iterator will return exactly `len()`
78 /// more times a [`Some(T)`] value, before returning [`None`].
79 /// This method has a default implementation, so you usually should not
80 /// implement it directly. However, if you can provide a more efficient
81 /// implementation, you can do so. See the [trait-level] docs for an
84 /// This function has the same safety guarantees as the
85 /// [`Iterator::size_hint`] function.
87 /// [trait-level]: ExactSizeIterator
95 /// // a finite range knows exactly how many times it will iterate
98 /// assert_eq!(5, five.len());
101 #[stable(feature = "rust1", since = "1.0.0")]
102 fn len(&self) -> usize {
103 let (lower
, upper
) = self.size_hint();
104 // Note: This assertion is overly defensive, but it checks the invariant
105 // guaranteed by the trait. If this trait were rust-internal,
106 // we could use debug_assert!; assert_eq! will check all Rust user
107 // implementations too.
108 assert_eq
!(upper
, Some(lower
));
112 /// Returns `true` if the iterator is empty.
114 /// This method has a default implementation using
115 /// [`ExactSizeIterator::len()`], so you don't need to implement it yourself.
122 /// #![feature(exact_size_is_empty)]
124 /// let mut one_element = std::iter::once(0);
125 /// assert!(!one_element.is_empty());
127 /// assert_eq!(one_element.next(), Some(0));
128 /// assert!(one_element.is_empty());
130 /// assert_eq!(one_element.next(), None);
133 #[unstable(feature = "exact_size_is_empty", issue = "35428")]
134 fn is_empty(&self) -> bool
{
139 #[stable(feature = "rust1", since = "1.0.0")]
140 impl<I
: ExactSizeIterator
+ ?Sized
> ExactSizeIterator
for &mut I
{
141 fn len(&self) -> usize {
144 fn is_empty(&self) -> bool
{