Skip to content

Commit

Permalink
Add support for IEEE 754 NaN / infinity
Browse files Browse the repository at this point in the history
This enables unpacking of 32-bit and 64-bit floating-point NaN,
+infinity and -infinity, to the values `:NaN`, `:inf` and `:"-inf"`, but
does not support packing those atoms back into Messagepack floats.
  • Loading branch information
CandyGumdrop authored and wisdm-callum committed Aug 15, 2019
1 parent c2c2ae1 commit af74d5f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/msgpax/unpacker.ex
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,13 @@ defmodule Msgpax.Unpacker do
quote(do: <<0xD2, value::32-signed>>),
quote(do: <<0xD3, value::64-signed>>)
] => quote(do: value),
# IEEE 754 NaN / infinity
[quote(do: <<0xCA, 0::1, 0b11111111::8, 0::23>>)] => :inf,
[quote(do: <<0xCA, 1::1, 0b11111111::8, 0::23>>)] => :"-inf",
[quote(do: <<0xCA, _sign::1, 0b11111111::8, _fraction::23>>)] => :NaN,
[quote(do: <<0xCB, 0::1, 0b11111111111::11, 0::52>>)] => :inf,
[quote(do: <<0xCB, 1::1, 0b11111111111::11, 0::52>>)] => :"-inf",
[quote(do: <<0xCB, _sign::1, 0b11111111111::11, _fraction::52>>)] => :NaN,
# Negative fixint
[quote(do: <<0b111::3, value::5>>)] => quote(do: value - 0b100000)
}
Expand Down
12 changes: 12 additions & 0 deletions test/msgpax_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,18 @@ defmodule MsgpaxTest do
assert_format 42.1, <<203>>
end

test "ieee 754 32-bit inf / nan" do
assert Msgpax.unpack(<<202, 0x7FC00000::32>>) == {:ok, :NaN}
assert Msgpax.unpack(<<202, 0x7F800000::32>>) == {:ok, :inf}
assert Msgpax.unpack(<<202, 0xFF800000::32>>) == {:ok, :"-inf"}
end

test "ieee 754 64-bit inf / nan" do
assert Msgpax.unpack(<<203, 0x7FF8000000000000::64>>) == {:ok, :NaN}
assert Msgpax.unpack(<<203, 0x7FF0000000000000::64>>) == {:ok, :inf}
assert Msgpax.unpack(<<203, 0xFFF0000000000000::64>>) == {:ok, :"-inf"}
end

test "positive fixint" do
assert_format 0, <<0>>
assert_format 127, <<127>>
Expand Down

0 comments on commit af74d5f

Please sign in to comment.