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

Commit

Permalink
Merge pull request #214 from cheradenine/serialize-f32
Browse files Browse the repository at this point in the history
Serialize f32
  • Loading branch information
dtolnay committed Sep 10, 2021
2 parents 7a340b2 + 7d07fe6 commit 045dfed
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
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

0 comments on commit 045dfed

Please sign in to comment.