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

Commit c420357

Browse files
author
john.burkhardt
committed
Adds explicit serialization for f32 to avoid rounding artifacts when promoting f32 to f64
1 parent 7a340b2 commit c420357

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

‎src/ser.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,16 @@ impl ser::Serializer for SerializerToYaml {
514514
}
515515

516516
fn serialize_f32(self, v: f32) -> Result<Yaml> {
517-
self.serialize_f64(v as f64)
517+
Ok(Yaml::Real(match v.classify() {
518+
num::FpCategory::Infinite if v.is_sign_positive() => ".inf".into(),
519+
num::FpCategory::Infinite => "-.inf".into(),
520+
num::FpCategory::Nan => ".nan".into(),
521+
_ => {
522+
let mut buf = vec![];
523+
::dtoa::write(&mut buf, v).unwrap();
524+
::std::str::from_utf8(&buf).unwrap().into()
525+
}
526+
}))
518527
}
519528

520529
fn serialize_f64(self, v: f64) -> Result<Yaml> {

‎tests/test_serde.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,16 @@ fn test_float() {
135135
assert!(float.is_nan());
136136
}
137137

138+
#[test]
139+
fn test_float32() {
140+
let thing: f32 = 25.6;
141+
let yaml = indoc! {"
142+
---
143+
25.6
144+
"};
145+
test_serde(&thing, yaml);
146+
}
147+
138148
#[test]
139149
fn test_vec() {
140150
let thing = vec![1, 2, 3];

0 commit comments

Comments
 (0)