From f671fbbec35f350981856b7f7969a20a5cf61e55 Mon Sep 17 00:00:00 2001 From: Jake Vossen Date: Tue, 5 Jan 2021 13:23:46 -0700 Subject: [PATCH 1/2] added sum trait for Duration --- src/oldtime.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/oldtime.rs b/src/oldtime.rs index 8656769c50..3d9575731c 100644 --- a/src/oldtime.rs +++ b/src/oldtime.rs @@ -372,6 +372,18 @@ impl Div for Duration { } } +impl<'a> std::iter::Sum<&'a Duration> for Duration { + fn sum>(iter: I) -> Duration { + iter.fold(Duration::zero(), |acc, x| acc + *x) + } +} + +impl std::iter::Sum for Duration { + fn sum>(iter: I) -> Duration { + iter.fold(Duration::zero(), |acc, x| acc + x) + } +} + impl fmt::Display for Duration { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // technically speaking, negative duration is not valid ISO 8601, @@ -626,6 +638,27 @@ mod tests { assert_eq!(Duration::seconds(-4) / -3, Duration::nanoseconds(1_333_333_333)); } + #[test] + fn test_duration_sum() { + let duration_list_1 = [Duration::zero(), Duration::seconds(1)]; + let sum_1: Duration = duration_list_1.iter().sum(); + assert_eq!(sum_1, Duration::seconds(1)); + + let duration_list_2 = + [Duration::zero(), Duration::seconds(1), Duration::seconds(6), Duration::seconds(10)]; + let sum_2: Duration = duration_list_2.iter().sum(); + assert_eq!(sum_2, Duration::seconds(17)); + + let duration_vec = vec![ + Duration::zero(), + Duration::seconds(1), + Duration::seconds(6), + Duration::seconds(10), + ]; + let sum_3: Duration = duration_vec.into_iter().sum(); + assert_eq!(sum_3, Duration::seconds(17)); + } + #[test] fn test_duration_fmt() { assert_eq!(Duration::zero().to_string(), "PT0S"); From d0b3d86a717f424f1b64096e05dc1d5e1afe72af Mon Sep 17 00:00:00 2001 From: Jake Vossen Date: Tue, 5 Jan 2021 13:27:05 -0700 Subject: [PATCH 2/2] added to changelog and authors --- AUTHORS.txt | 1 + CHANGELOG.md | 1 + 2 files changed, 2 insertions(+) diff --git a/AUTHORS.txt b/AUTHORS.txt index 9501a9d059..5a07a48908 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -22,6 +22,7 @@ Eunchong Yu Frans Skarman Huon Wilson Igor Gnatenko +Jake Vossen Jim Turner Jisoo Park Joe Wilm diff --git a/CHANGELOG.md b/CHANGELOG.md index 16a9063b60..e922595d5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ Versions with only mechanical changes will be omitted from the following list. * Add support for microseconds timestamps serde serialization/deserialization (#304) * Fix `DurationRound` is not TZ aware (#495) * Implement `DurationRound` for `NaiveDateTime` +* Implement `std::iter::Sum` for `Duration` ## 0.4.19