Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

deer: implement Deserialize for core::time #2390

Merged
merged 15 commits into from
Apr 14, 2023
1 change: 1 addition & 0 deletions libs/deer/src/impls/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ mod non_zero;
mod option;
mod string;
mod sync;
mod time;
mod unit;
13 changes: 13 additions & 0 deletions libs/deer/src/impls/core/time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use core::time::Duration;

use error_stack::Result;

use crate::{error::DeserializeError, Deserialize, Deserializer};

impl<'de> Deserialize<'de> for Duration {
type Reflection = <f64 as Deserialize<'de>>::Reflection;

fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, DeserializeError> {
f64::deserialize(de).map(Self::from_secs_f64)
}
}
19 changes: 19 additions & 0 deletions libs/deer/tests/test_impls_core_time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use core::time::Duration;

use deer_desert::{assert_tokens_with_assertion, Token};
use proptest::prelude::*;

#[cfg(not(miri))]
proptest! {
#[test]
fn duration_ok(value in any::<Duration>()) {
let input = value.as_secs_f64();

assert_tokens_with_assertion(|received: Duration| {
// due to the inherent imprecise nature of floats, we cannot use `assert_eq!`
// instead we need to check if the difference between both values is <= ε
// (which is the upper bound on the relative approximation error)
assert!((received.as_secs_f64() - value.as_secs_f64()).abs() <= f64::EPSILON);
}, &[Token::Number(input.into())]);
}
}