core/iter/traits/unchecked_iterator.rs
1use crate::iter::TrustedLen;
2
3/// [`TrustedLen`] cannot have methods, so this allows augmenting it.
4///
5/// It currently requires `TrustedLen` because it's unclear whether it's
6/// reasonably possible to depend on the `size_hint` of anything else.
7pub(crate) trait UncheckedIterator: TrustedLen {
8    /// Gets the next item from a non-empty iterator.
9    ///
10    /// Because there's always a value to return, that means it can return
11    /// the `Item` type directly, without wrapping it in an `Option`.
12    ///
13    /// # Safety
14    ///
15    /// This can only be called if `size_hint().0 != 0`, guaranteeing that
16    /// there's at least one item available.
17    ///
18    /// Otherwise (aka when `size_hint().1 == Some(0)`), this is UB.
19    ///
20    /// # Note to Implementers
21    ///
22    /// This has a default implementation using [`Option::unwrap_unchecked`].
23    /// That's probably sufficient if your `next` *always* returns `Some`,
24    /// such as for infinite iterators.  In more complicated situations, however,
25    /// sometimes there can still be `insertvalue`/`assume`/`extractvalue`
26    /// instructions remaining in the IR from the `Option` handling, at which
27    /// point you might want to implement this manually instead.
28    #[unstable(feature = "trusted_len_next_unchecked", issue = "37572")]
29    #[inline]
30    #[cfg(not(feature = "ferrocene_certified"))]
31    unsafe fn next_unchecked(&mut self) -> Self::Item {
32        let opt = self.next();
33        // SAFETY: The caller promised that we're not empty, and
34        // `Self: TrustedLen` so we can actually trust the `size_hint`.
35        unsafe { opt.unwrap_unchecked() }
36    }
37    // Ferrocene addition: gate the default implementation
38    #[cfg(feature = "ferrocene_certified")]
39    unsafe fn next_unchecked(&mut self) -> Self::Item;
40}