Skip to content

Commit

Permalink
impl serde::Serialize and serde::Deserialize for TimeDelta (#1599)
Browse files Browse the repository at this point in the history
  • Loading branch information
Awpteamoose authored Sep 16, 2024
1 parent 081c648 commit c8defc7
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/time_delta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,47 @@ impl arbitrary::Arbitrary<'_> for TimeDelta {
}
}

#[cfg(feature = "serde")]
mod serde {
use super::TimeDelta;
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};

impl Serialize for TimeDelta {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
<(i64, i32) as Serialize>::serialize(&(self.secs, self.nanos), serializer)
}
}

impl<'de> Deserialize<'de> for TimeDelta {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let (secs, nanos) = <(i64, i32) as Deserialize>::deserialize(deserializer)?;
TimeDelta::new(secs, nanos as u32).ok_or(Error::custom("TimeDelta out of bounds"))
}
}

#[cfg(test)]
mod tests {
use super::{super::MAX, TimeDelta};

#[test]
fn test_serde() {
let duration = TimeDelta::new(123, 456).unwrap();
assert_eq!(
serde_json::from_value::<TimeDelta>(serde_json::to_value(duration).unwrap())
.unwrap(),
duration
);
}

#[test]
#[should_panic(expected = "TimeDelta out of bounds")]
fn test_serde_oob_panic() {
let _ =
serde_json::from_value::<TimeDelta>(serde_json::json!([MAX.secs + 1, 0])).unwrap();
}
}
}

#[cfg(test)]
mod tests {
use super::OutOfRangeError;
Expand Down

0 comments on commit c8defc7

Please sign in to comment.