diff --git a/AUTHORS.txt b/AUTHORS.txt index e4d7d2ad1d..caff57915c 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 39174ef312..fe69ed4ab6 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` * Add `DateTime::from_local()` to construct from given local date and time (#572) * Add a function that calculates the number of years elapsed between now and a given `Date` or `DateTime` (#557) * Correct build for wasm32-unknown-emscripten target (#568) diff --git a/src/oldtime.rs b/src/oldtime.rs index 57d199e2d8..eb0c5bcf20 100644 --- a/src/oldtime.rs +++ b/src/oldtime.rs @@ -377,6 +377,20 @@ impl Div for Duration { } } +#[cfg(any(feature = "std", test))] +impl<'a> std::iter::Sum<&'a Duration> for Duration { + fn sum>(iter: I) -> Duration { + iter.fold(Duration::zero(), |acc, x| acc + *x) + } +} + +#[cfg(any(feature = "std", test))] +impl std::iter::Sum for Duration { + fn sum>(iter: I) -> Duration { + iter.fold(Duration::zero(), |acc, x| acc + x) + } +} + impl fmt::Display for Duration { /// Format a duration using the [ISO 8601] format /// @@ -634,6 +648,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");