Skip to content

Commit

Permalink
Implement std::iter::Sum for Duration (#522)
Browse files Browse the repository at this point in the history
  • Loading branch information
jakevossen5 committed Jun 9, 2022
1 parent 752e69a commit 7c0bc31
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions AUTHORS.txt
Expand Up @@ -22,6 +22,7 @@ Eunchong Yu <kroisse@gmail.com>
Frans Skarman <frans.skarman@gmail.com>
Huon Wilson <dbau.pp+github@gmail.com>
Igor Gnatenko <ignatenko@redhat.com>
Jake Vossen <jake@vossen.dev>
Jim Turner <jturner314@gmail.com>
Jisoo Park <xxxyel@gmail.com>
Joe Wilm <joe@jwilm.com>
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -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)
Expand Down
35 changes: 35 additions & 0 deletions src/oldtime.rs
Expand Up @@ -377,6 +377,20 @@ impl Div<i32> for Duration {
}
}

#[cfg(any(feature = "std", test))]
impl<'a> std::iter::Sum<&'a Duration> for Duration {
fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
iter.fold(Duration::zero(), |acc, x| acc + *x)
}
}

#[cfg(any(feature = "std", test))]
impl std::iter::Sum<Duration> for Duration {
fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
iter.fold(Duration::zero(), |acc, x| acc + x)
}
}

impl fmt::Display for Duration {
/// Format a duration using the [ISO 8601] format
///
Expand Down Expand Up @@ -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");
Expand Down

0 comments on commit 7c0bc31

Please sign in to comment.