From dc3ab70b58ecc619dbebef3433f4af6d07e219fa Mon Sep 17 00:00:00 2001 From: Jeremy Smart Date: Tue, 4 Nov 2025 11:38:45 -0500 Subject: [PATCH] add Option::into_flat_iter --- library/core/src/option.rs | 60 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index e3c4758bc6af5..8fe3c0c4d3510 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -2007,6 +2007,30 @@ impl Option { } } +impl Option { + /// Transforms an optional iterator into an iterator. + /// + /// If `self` is `None`, the resulting iterator is empty. + /// Otherwise, an iterator is made from the `Some` value and returned. + /// # Examples + /// ``` + /// #![feature(option_into_flat_iter)] + /// + /// let o1 = Some([1, 2]); + /// let o2 = None::<&[usize]>; + /// + /// assert_eq!(o1.into_flat_iter().collect::>(), [1, 2]); + /// assert_eq!(o2.into_flat_iter().collect::>(), Vec::<&usize>::new()); + /// ``` + #[unstable(feature = "option_into_flat_iter", issue = "148441")] + pub fn into_flat_iter(self) -> OptionFlatten + where + T: IntoIterator, + { + OptionFlatten { iter: self.map(IntoIterator::into_iter) } + } +} + impl Option<(T, U)> { /// Unzips an option containing a tuple of two options. /// @@ -2569,6 +2593,42 @@ impl FusedIterator for IntoIter {} #[unstable(feature = "trusted_len", issue = "37572")] unsafe impl TrustedLen for IntoIter {} +/// The iterator produced by [`Option::into_flat_iter`]. See its documentation for more. +#[derive(Clone, Debug)] +#[unstable(feature = "option_into_flat_iter", issue = "148441")] +pub struct OptionFlatten { + iter: Option, +} + +#[unstable(feature = "option_into_flat_iter", issue = "148441")] +impl Iterator for OptionFlatten { + type Item = A::Item; + + fn next(&mut self) -> Option { + self.iter.as_mut()?.next() + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.as_ref().map(|i| i.size_hint()).unwrap_or((0, Some(0))) + } +} + +#[unstable(feature = "option_into_flat_iter", issue = "148441")] +impl DoubleEndedIterator for OptionFlatten { + fn next_back(&mut self) -> Option { + self.iter.as_mut()?.next_back() + } +} + +#[unstable(feature = "option_into_flat_iter", issue = "148441")] +impl ExactSizeIterator for OptionFlatten {} + +#[unstable(feature = "option_into_flat_iter", issue = "148441")] +impl FusedIterator for OptionFlatten {} + +#[unstable(feature = "option_into_flat_iter", issue = "148441")] +unsafe impl TrustedLen for OptionFlatten {} + ///////////////////////////////////////////////////////////////////////////// // FromIterator /////////////////////////////////////////////////////////////////////////////