Skip to content

Commit

Permalink
fix: Preserve sign of NaN when serializing f32
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Oct 26, 2023
1 parent af46f3f commit 9bdfed0
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
4 changes: 3 additions & 1 deletion crates/toml/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -921,7 +921,9 @@ impl ser::Serializer for ValueSerializer {
}

fn serialize_f32(self, value: f32) -> Result<Value, crate::ser::Error> {
self.serialize_f64(value.into())
// Preserve sign of NaN. The `as` produces a nondeterministic sign.
let sign = if value.is_sign_positive() { 1.0 } else { -1.0 };
self.serialize_f64((value as f64).copysign(sign))
}

fn serialize_f64(self, value: f64) -> Result<Value, crate::ser::Error> {
Expand Down
4 changes: 3 additions & 1 deletion crates/toml_edit/src/ser/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,9 @@ impl serde::ser::Serializer for ValueSerializer {
}

fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
self.serialize_f64(v as f64)
// Preserve sign of NaN. The `as` produces a nondeterministic sign.
let sign = if v.is_sign_positive() { 1.0 } else { -1.0 };
self.serialize_f64((v as f64).copysign(sign))
}

fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
Expand Down

0 comments on commit 9bdfed0

Please sign in to comment.