@@ -360,3 +360,61 @@ impl Extend<()> for () {
360360 }
361361 fn extend_one ( & mut self , _item : ( ) ) { }
362362}
363+
364+ #[ stable( feature = "extend_for_tuple" , since = "1.56.0" ) ]
365+ impl < A , B , ExtendA , ExtendB > Extend < ( A , B ) > for ( ExtendA , ExtendB )
366+ where
367+ ExtendA : Extend < A > ,
368+ ExtendB : Extend < B > ,
369+ {
370+ /// Allows to `extend` a tuple of collections that also implement `Extend`.
371+ ///
372+ /// See also: [`Iterator::unzip`]
373+ ///
374+ /// # Examples
375+ /// ```
376+ /// let mut tuple = (vec![0], vec![1]);
377+ /// tuple.extend(vec![(2, 3), (4, 5), (6, 7)]);
378+ /// assert_eq!(tuple.0, vec![0, 2, 4, 6]);
379+ /// assert_eq!(tuple.1, vec![1, 3, 5, 7]);
380+ ///
381+ /// // also allows for arbitrarily nested tuples
382+ /// let mut nested_tuple = (vec![(1, -1)], vec![(2, -2)]);
383+ /// nested_tuple.extend(vec![((3, -3), (4, -4)), ((5, -5), (6, -6))]);
384+ ///
385+ /// assert_eq!(nested_tuple.0, vec![(1, -1), (3, -3), (5, -5)]);
386+ /// assert_eq!(nested_tuple.1, vec![(2, -2), (4, -4), (6, -6)]);
387+ /// ```
388+ fn extend < T : IntoIterator < Item = ( A , B ) > > ( & mut self , into_iter : T ) {
389+ let ( a, b) = self ;
390+ let iter = into_iter. into_iter ( ) ;
391+
392+ fn extend < ' a , A , B > (
393+ a : & ' a mut impl Extend < A > ,
394+ b : & ' a mut impl Extend < B > ,
395+ ) -> impl FnMut ( ( ) , ( A , B ) ) + ' a {
396+ move |( ) , ( t, u) | {
397+ a. extend_one ( t) ;
398+ b. extend_one ( u) ;
399+ }
400+ }
401+
402+ let ( lower_bound, _) = iter. size_hint ( ) ;
403+ if lower_bound > 0 {
404+ a. extend_reserve ( lower_bound) ;
405+ b. extend_reserve ( lower_bound) ;
406+ }
407+
408+ iter. fold ( ( ) , extend ( a, b) ) ;
409+ }
410+
411+ fn extend_one ( & mut self , item : ( A , B ) ) {
412+ self . 0 . extend_one ( item. 0 ) ;
413+ self . 1 . extend_one ( item. 1 ) ;
414+ }
415+
416+ fn extend_reserve ( & mut self , additional : usize ) {
417+ self . 0 . extend_reserve ( additional) ;
418+ self . 1 . extend_reserve ( additional) ;
419+ }
420+ }
0 commit comments