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

Impl serde::Serialize and serde::Deserialize for TimeDelta #1599

Merged
merged 6 commits into from
Sep 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"))
Copy link
Collaborator

@pitdicker pitdicker Sep 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, comment after the merge. What happens if nanos is negative?

Edit: never mind, it works out.

}
}

#[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
Loading