@@ -524,17 +524,47 @@ impl DivAssign<u32> for Duration {
524524 }
525525}
526526
527+ macro_rules! sum_durations {
528+ ( $iter: expr) => { {
529+ let mut total_secs: u64 = 0 ;
530+ let mut total_nanos: u64 = 0 ;
531+
532+ for entry in $iter {
533+ total_secs = total_secs
534+ . checked_add( entry. secs)
535+ . expect( "overflow in iter::sum over durations" ) ;
536+ total_nanos = match total_nanos. checked_add( entry. nanos as u64 ) {
537+ Some ( n) => n,
538+ None => {
539+ total_secs = total_secs
540+ . checked_add( total_nanos / NANOS_PER_SEC as u64 )
541+ . expect( "overflow in iter::sum over durations" ) ;
542+ ( total_nanos % NANOS_PER_SEC as u64 ) + entry. nanos as u64
543+ }
544+ } ;
545+ }
546+ total_secs = total_secs
547+ . checked_add( total_nanos / NANOS_PER_SEC as u64 )
548+ . expect( "overflow in iter::sum over durations" ) ;
549+ total_nanos = total_nanos % NANOS_PER_SEC as u64 ;
550+ Duration {
551+ secs: total_secs,
552+ nanos: total_nanos as u32 ,
553+ }
554+ } } ;
555+ }
556+
527557#[ stable( feature = "duration_sum" , since = "1.16.0" ) ]
528558impl Sum for Duration {
529559 fn sum < I : Iterator < Item =Duration > > ( iter : I ) -> Duration {
530- iter . fold ( Duration :: new ( 0 , 0 ) , |a , b| a + b )
560+ sum_durations ! ( iter )
531561 }
532562}
533563
534564#[ stable( feature = "duration_sum" , since = "1.16.0" ) ]
535565impl < ' a > Sum < & ' a Duration > for Duration {
536566 fn sum < I : Iterator < Item =& ' a Duration > > ( iter : I ) -> Duration {
537- iter . fold ( Duration :: new ( 0 , 0 ) , |a , b| a + * b )
567+ sum_durations ! ( iter )
538568 }
539569}
540570
0 commit comments