@@ -4034,6 +4034,62 @@ pub trait Iterator {
40344034 {
40354035 unreachable ! ( "Always specialized" ) ;
40364036 }
4037+
4038+ /// Checks if the iterator contains *exactly* one element.
4039+ /// If so, returns this one element.
4040+ ///
4041+ /// See also [`collect_array`](Iterator::collect_array) for lengths other than `1`.
4042+ ///
4043+ /// # Examples
4044+ ///
4045+ /// ```
4046+ /// #![feature(exact_length_collection)]
4047+ ///
4048+ /// assert_eq!([1].into_iter().exactly_one(), Some(1));
4049+ /// assert_eq!([].into_iter().exactly_one(), None::<()>);
4050+ ///
4051+ /// // There is exactly one even integer in the array:
4052+ /// assert_eq!([1, 2, 3].into_iter().filter(|x| x % 2 == 0).exactly_one(), Some(2));
4053+ /// // But there are two odds, which is too many:
4054+ /// assert_eq!([1, 2, 3].into_iter().filter(|x| x % 2 == 1).exactly_one(), None);
4055+ /// ```
4056+ #[ inline]
4057+ #[ unstable( feature = "exact_length_collection" , issue = "149266" ) ]
4058+ fn exactly_one ( self ) -> Option < Self :: Item >
4059+ where
4060+ Self : Sized ,
4061+ {
4062+ self . collect_array :: < 1 > ( ) . map ( |[ i] | i)
4063+ }
4064+
4065+ /// Checks if an iterator has *exactly* `N` elements.
4066+ /// If so, returns those `N` elements in an array.
4067+ ///
4068+ /// See also [`exactly_one`](Iterator::exactly_one) when expecting a single element.
4069+ ///
4070+ /// # Examples
4071+ ///
4072+ /// ```
4073+ /// #![feature(exact_length_collection)]
4074+ ///
4075+ /// assert_eq!([1, 2, 3, 4].into_iter().collect_array(), Some([1, 2, 3, 4]));
4076+ /// assert_eq!([1, 2].into_iter().chain([3, 4]).collect_array(), Some([1, 2, 3, 4]));
4077+ ///
4078+ /// // Iterator contains too few elements:
4079+ /// assert_eq!([1, 2].into_iter().collect_array::<4>(), None);
4080+ /// // Iterator contains too many elements:
4081+ /// assert_eq!([1, 2, 3, 4, 5].into_iter().collect_array::<4>(), None);
4082+ /// // Taking 4 makes it work again:
4083+ /// assert_eq!([1, 2, 3, 4, 5].into_iter().take(4).collect_array(), Some([1, 2, 3, 4]));
4084+ /// ```
4085+ #[ inline]
4086+ #[ unstable( feature = "exact_length_collection" , issue = "149266" ) ]
4087+ fn collect_array < const N : usize > ( mut self ) -> Option < [ Self :: Item ; N ] >
4088+ where
4089+ Self : Sized ,
4090+ {
4091+ self . next_chunk ( ) . ok ( ) . filter ( |_| self . next ( ) . is_none ( ) )
4092+ }
40374093}
40384094
40394095trait SpecIterEq < B : Iterator > : Iterator {
0 commit comments