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

Serialize f32 #214

Merged
merged 2 commits into from Sep 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/ser.rs
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
32 changes: 32 additions & 0 deletions tests/test_serde.rs
Expand Up @@ -135,6 +135,38 @@ 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);

let thing = f32::INFINITY;
let yaml = indoc! {"
---
.inf
"};
test_serde(&thing, yaml);

let thing = f32::NEG_INFINITY;
let yaml = indoc! {"
---
-.inf
"};
test_serde(&thing, yaml);

let single_float: f32 = serde_yaml::from_str(indoc! {"
---
.nan
"})
.unwrap();
assert!(single_float.is_nan());

}

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