mirror of
https://github.com/chronotope/chrono.git
synced 2025-09-28 05:21:39 +00:00
Implement std::iter::Sum for Duration (#522)
This commit is contained in:
parent
752e69ae1f
commit
7c0bc31a63
@ -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>
|
||||
|
@ -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)
|
||||
|
@ -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
|
||||
///
|
||||
@ -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");
|
||||
|
Loading…
x
Reference in New Issue
Block a user