| 1 | use 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. |
| 7 | pub(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 | unsafe fn next_unchecked(&mut self) -> Self::Item { |
| 31 | let opt = self.next(); |
| 32 | // SAFETY: The caller promised that we're not empty, and |
| 33 | // `Self: TrustedLen` so we can actually trust the `size_hint`. |
| 34 | unsafe { opt.unwrap_unchecked() } |
| 35 | } |
| 36 | } |
| 37 | |