@@ -524,17 +524,47 @@ impl DivAssign<u32> for Duration {
524
524
}
525
525
}
526
526
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
+
527
557
#[ stable( feature = "duration_sum" , since = "1.16.0" ) ]
528
558
impl Sum for Duration {
529
559
fn sum < I : Iterator < Item =Duration > > ( iter : I ) -> Duration {
530
- iter . fold ( Duration :: new ( 0 , 0 ) , |a , b| a + b )
560
+ sum_durations ! ( iter )
531
561
}
532
562
}
533
563
534
564
#[ stable( feature = "duration_sum" , since = "1.16.0" ) ]
535
565
impl < ' a > Sum < & ' a Duration > for Duration {
536
566
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 )
538
568
}
539
569
}
540
570
0 commit comments