Skip to content

Commit

Permalink
Fix sub-second negative Duration serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
vriesk authored and jhpratt committed Oct 8, 2024
1 parent 9a7603f commit b3b5fb9
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
8 changes: 8 additions & 0 deletions tests/serde/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -842,6 +842,14 @@ fn duration() {
&Duration::ZERO.readable(),
&[Token::BorrowedStr("0.000000000")],
);
assert_tokens(
&Duration::nanoseconds(123).readable(),
&[Token::BorrowedStr("0.000000123")],
);
assert_tokens(
&Duration::nanoseconds(-123).readable(),
&[Token::BorrowedStr("-0.000000123")],
);
}

#[test]
Expand Down
7 changes: 4 additions & 3 deletions time/src/serde/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,10 @@ impl Serialize for Duration {
#[cfg(feature = "serde-human-readable")]
if serializer.is_human_readable() {
return serializer.collect_str(&format_args!(
"{}.{:>09}",
self.whole_seconds(),
self.subsec_nanoseconds().abs()
"{}{}.{:>09}",
if self.is_negative() { "-" } else { "" },
self.whole_seconds().unsigned_abs(),
self.subsec_nanoseconds().abs(),
));
}

Expand Down
5 changes: 4 additions & 1 deletion time/src/serde/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ impl<'a> de::Visitor<'a> for Visitor<Duration> {
de::Error::invalid_value(de::Unexpected::Str(nanoseconds), &"nanoseconds")
})?;

if seconds < 0 {
if seconds < 0
// make sure sign does not disappear when seconds == 0
|| (seconds == 0 && value.starts_with("-"))
{
nanoseconds *= -1;
}

Expand Down

0 comments on commit b3b5fb9

Please sign in to comment.