Skip to content

Commit

Permalink
feat(enc.float): define NaN and Inf
Browse files Browse the repository at this point in the history
  • Loading branch information
ernado committed Oct 31, 2021
1 parent b14618b commit b47da2c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
4 changes: 4 additions & 0 deletions enc_float.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package jx

// Float32 writes float32.
//
// NB: Infinities and NaN are represented as null.
func (e *Encoder) Float32(v float32) { e.float(float64(v), 32) }

// Float64 writes float64.
//
// NB: Infinities and NaN are represented as null.
func (e *Encoder) Float64(v float64) { e.float(v, 64) }
14 changes: 12 additions & 2 deletions enc_float_bits.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,19 @@ import (
"strconv"
)

// From go std sources, strconv/ftoa.go

func (e *Encoder) float(v float64, bits int) {
if math.IsNaN(v) || math.IsInf(v, 0) {
// Like in ECMA:
// NaN and Infinity regardless of sign are represented
// as the String null.
//
// JSON.stringify({"foo":NaN}) -> {"foo":null}
e.Null()
return
}

// From go std sources, strconv/ftoa.go:

// Convert as if by ES6 number to string conversion.
// This matches most other JSON generators.
// See golang.org/issue/6384 and golang.org/issue/14135.
Expand Down
18 changes: 18 additions & 0 deletions float_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,21 @@ func TestDecoder_FloatEOF(t *testing.T) {
_, err := d.Float32()
require.ErrorIs(t, err, io.ErrUnexpectedEOF)
}

func TestEncoder_FloatNanInf(t *testing.T) {
for _, f := range []float64{
math.NaN(),
math.Inf(-1),
math.Inf(1),
} {
var e Encoder
e.Float64(f)
e.More()
e.Float32(float32(f))

d := DecodeBytes(e.Bytes())
require.NoError(t, d.Null())
requireElem(t, d)
require.NoError(t, d.Null())
}
}

0 comments on commit b47da2c

Please sign in to comment.