11package jsoniter
22
33import (
4+ "fmt"
45 "math"
56 "strconv"
67)
@@ -13,6 +14,10 @@ func init() {
1314
1415// WriteFloat32 write float32 to stream
1516func (stream * Stream ) WriteFloat32 (val float32 ) {
17+ if math .IsInf (float64 (val ), 0 ) || math .IsNaN (float64 (val )) {
18+ stream .Error = fmt .Errorf ("unsupported value: %f" , val )
19+ return
20+ }
1621 abs := math .Abs (float64 (val ))
1722 fmt := byte ('f' )
1823 // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right.
@@ -26,6 +31,10 @@ func (stream *Stream) WriteFloat32(val float32) {
2631
2732// WriteFloat32Lossy write float32 to stream with ONLY 6 digits precision although much much faster
2833func (stream * Stream ) WriteFloat32Lossy (val float32 ) {
34+ if math .IsInf (float64 (val ), 0 ) || math .IsNaN (float64 (val )) {
35+ stream .Error = fmt .Errorf ("unsupported value: %f" , val )
36+ return
37+ }
2938 if val < 0 {
3039 stream .writeByte ('-' )
3140 val = - val
@@ -54,6 +63,10 @@ func (stream *Stream) WriteFloat32Lossy(val float32) {
5463
5564// WriteFloat64 write float64 to stream
5665func (stream * Stream ) WriteFloat64 (val float64 ) {
66+ if math .IsInf (val , 0 ) || math .IsNaN (val ) {
67+ stream .Error = fmt .Errorf ("unsupported value: %f" , val )
68+ return
69+ }
5770 abs := math .Abs (val )
5871 fmt := byte ('f' )
5972 // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right.
@@ -67,6 +80,10 @@ func (stream *Stream) WriteFloat64(val float64) {
6780
6881// WriteFloat64Lossy write float64 to stream with ONLY 6 digits precision although much much faster
6982func (stream * Stream ) WriteFloat64Lossy (val float64 ) {
83+ if math .IsInf (val , 0 ) || math .IsNaN (val ) {
84+ stream .Error = fmt .Errorf ("unsupported value: %f" , val )
85+ return
86+ }
7087 if val < 0 {
7188 stream .writeByte ('-' )
7289 val = - val
0 commit comments