Skip to content

Commit

Permalink
deer: implement Deserialize for core::time (#2390)
Browse files Browse the repository at this point in the history
* feat: init cell

* feat: pull in code from #1875

* feat: test cells

* test: unsafe variants

* test: reflection passthrough

* fix: lint

* Update test_impls_core_cell.rs

* chore: convert from #1875

* test: duration deserialization

* test: time via approx

* fix: miri

* feat: implement relative assert ourselves

* chore: grammar c:
  • Loading branch information
indietyp authored Apr 14, 2023
1 parent 762b43e commit c5a925c
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions libs/deer/src/impls/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ mod num;
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())]);
}
}

0 comments on commit c5a925c

Please sign in to comment.