Skip to content
This repository has been archived by the owner on Mar 25, 2024. It is now read-only.

Commit

Permalink
Adds explicit serialization for f32 to avoid rounding artifacts when …
Browse files Browse the repository at this point in the history
…promoting f32 to f64
  • Loading branch information
john.burkhardt committed Sep 10, 2021
1 parent 7a340b2 commit c420357
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,16 @@ impl ser::Serializer for SerializerToYaml {
}

fn serialize_f32(self, v: f32) -> Result<Yaml> {
self.serialize_f64(v as f64)
Ok(Yaml::Real(match v.classify() {
num::FpCategory::Infinite if v.is_sign_positive() => ".inf".into(),
num::FpCategory::Infinite => "-.inf".into(),
num::FpCategory::Nan => ".nan".into(),
_ => {
let mut buf = vec![];
::dtoa::write(&mut buf, v).unwrap();
::std::str::from_utf8(&buf).unwrap().into()
}
}))
}

fn serialize_f64(self, v: f64) -> Result<Yaml> {
Expand Down
10 changes: 10 additions & 0 deletions tests/test_serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,16 @@ fn test_float() {
assert!(float.is_nan());
}

#[test]
fn test_float32() {
let thing: f32 = 25.6;
let yaml = indoc! {"
---
25.6
"};
test_serde(&thing, yaml);
}

#[test]
fn test_vec() {
let thing = vec![1, 2, 3];
Expand Down

0 comments on commit c420357

Please sign in to comment.