Repository: time-rs/time (language: rust)

Issue:
implement `std::iter::Sum` for `Duration`?
Summing a sequence of durations is a useful operation. In fact, `std::time::Duration` implements `std::iter::Sum`. Any reason why this implementation was omitted in `time`?


Discussion / hints:
Not really. I can do this at some point :+1:
That would be great, thanks!

Fix patch:
diff --git a/src/duration.rs b/src/duration.rs
index 55b0b0b54..f9b686058 100644
--- a/src/duration.rs
+++ b/src/duration.rs
@@ -1,6 +1,7 @@
 use core::cmp::Ordering;
 use core::convert::{TryFrom, TryInto};
 use core::fmt;
+use core::iter::Sum;
 use core::ops::{Add, Div, Mul, Neg, Sub, SubAssign};
 use core::time::Duration as StdDuration;
 
@@ -953,4 +954,16 @@ impl PartialOrd<Duration> for StdDuration {
         rhs.partial_cmp(self).map(Ordering::reverse)
     }
 }
+
+impl Sum<Duration> for Duration {
+    fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
+        iter.reduce(|a, b| a + b).unwrap_or_default()
+    }
+}
+
+impl<'a> Sum<&'a Duration> for Duration {
+    fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
+        iter.copied().sum()
+    }
+}
 // endregion trait impls


Test patch:
diff --git a/tests/integration/duration.rs b/tests/integration/duration.rs
index 71c561410..75127f0b2 100644
--- a/tests/integration/duration.rs
+++ b/tests/integration/duration.rs
@@ -732,3 +732,17 @@ fn arithmetic_regression() {
     assert_eq!(subtracted.whole_seconds(), 3);
     assert_eq!(subtracted.subsec_milliseconds(), 200);
 }
+
+#[test]
+fn sum_iter_ref() {
+    let i = vec![1.6.seconds(), 1.6.seconds()];
+    let sum = i.iter().sum::<Duration>();
+    assert_eq!(sum, 3.2.seconds());
+}
+
+#[test]
+fn sum_iter() {
+    let i = vec![1.6.seconds(), 1.6.seconds()];
+    let sum = i.into_iter().sum::<Duration>();
+    assert_eq!(sum, 3.2.seconds());
+}