Skip to content

Commit

Permalink
YAML: correctly serialize infinity and NaN (crystal-lang#9780)
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite authored Sep 30, 2020
1 parent b34dd43 commit d97fe3f
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
34 changes: 34 additions & 0 deletions spec/std/yaml/serialization_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,19 @@ describe "YAML serialization" do

it "does Float32#from_yaml" do
Float32.from_yaml("1.5").should eq(1.5_f32)
Float32.from_yaml(".nan").nan?.should be_true
Float32.from_yaml(".inf").should eq(Float32::INFINITY)
Float32.from_yaml("-.inf").should eq(-Float32::INFINITY)
end

it "does Float64#from_yaml" do
value = Float64.from_yaml("1.5")
value.should eq(1.5)
value.should be_a(Float64)

Float64.from_yaml(".nan").nan?.should be_true
Float64.from_yaml(".inf").should eq(Float64::INFINITY)
Float64.from_yaml("-.inf").should eq(-Float64::INFINITY)
end

it "does Array#from_yaml" do
Expand Down Expand Up @@ -276,10 +282,38 @@ describe "YAML serialization" do
Int32.from_yaml(1.to_yaml).should eq(1)
end

it "does for Float32" do
Float32.from_yaml(1.5_f32.to_yaml).should eq(1.5_f32)
end

it "does for Float32 (infinity)" do
Float32.from_yaml(Float32::INFINITY.to_yaml).should eq(Float32::INFINITY)
end

it "does for Float32 (-infinity)" do
Float32.from_yaml((-Float32::INFINITY).to_yaml).should eq(-Float32::INFINITY)
end

it "does for Float32 (nan)" do
Float32.from_yaml(Float32::NAN.to_yaml).nan?.should be_true
end

it "does for Float64" do
Float64.from_yaml(1.5.to_yaml).should eq(1.5)
end

it "does for Float64 (infinity)" do
Float64.from_yaml(Float64::INFINITY.to_yaml).should eq(Float64::INFINITY)
end

it "does for Float64 (-infinity)" do
Float64.from_yaml((-Float64::INFINITY).to_yaml).should eq(-Float64::INFINITY)
end

it "does for Float64 (nan)" do
Float64.from_yaml(Float64::NAN.to_yaml).nan?.should be_true
end

it "does for String" do
String.from_yaml("hello".to_yaml).should eq("hello")
end
Expand Down
15 changes: 15 additions & 0 deletions src/yaml/to_yaml.cr
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,21 @@ struct Number
end
end

struct Float
def to_yaml(yaml : YAML::Nodes::Builder)
infinite = self.infinite?
if infinite == 1
yaml.scalar(".inf")
elsif infinite == -1
yaml.scalar("-.inf")
elsif nan?
yaml.scalar(".nan")
else
yaml.scalar self.to_s
end
end
end

struct Nil
def to_yaml(yaml : YAML::Nodes::Builder)
yaml.scalar ""
Expand Down

0 comments on commit d97fe3f

Please sign in to comment.