Ver código fonte

Fixed JSON serialisation of NaN and +/-Infinity

Dmitry Panov 9 anos atrás
pai
commit
9cf7286bea
2 arquivos alterados com 50 adições e 1 exclusões
  1. 8 1
      builtin_json.go
  2. 42 0
      runtime_test.go

+ 8 - 1
builtin_json.go

@@ -6,6 +6,7 @@ import (
 	"fmt"
 	"io"
 	"strings"
+	"math"
 )
 
 var hex = "0123456789abcdef"
@@ -336,8 +337,14 @@ func (ctx *_builtinJSON_stringifyContext) str(key Value, holder *Object) bool {
 		}
 	case valueString:
 		ctx.quote(value1)
-	case valueInt, valueFloat:
+	case valueInt:
 		ctx.buf.WriteString(value.String())
+	case valueFloat:
+		if !math.IsNaN(float64(value1)) && !math.IsInf(float64(value1), 0) {
+			ctx.buf.WriteString(value.String())
+		} else {
+			ctx.buf.WriteString("null")
+		}
 	case valueNull:
 		ctx.buf.WriteString("null")
 	case *Object:

+ 42 - 0
runtime_test.go

@@ -514,6 +514,48 @@ func TestJSONObjectInArray(t *testing.T) {
 	testScript1(SCRIPT, valueTrue, t)
 }
 
+func TestJSONQuirkyNumbers(t *testing.T) {
+	const SCRIPT = `
+	var s;
+	s = JSON.stringify(NaN);
+	if (s != "null") {
+		throw new Error("NaN: " + s);
+	}
+
+	s = JSON.stringify(Infinity);
+	if (s != "null") {
+		throw new Error("Infinity: " + s);
+	}
+
+	s = JSON.stringify(-Infinity);
+	if (s != "null") {
+		throw new Error("-Infinity: " + s);
+	}
+
+	`
+
+	testScript1(SCRIPT, _undefined, t)
+}
+
+func TestJSONNil(t *testing.T) {
+	const SCRIPT = `
+	JSON.stringify(i);
+	`
+
+	vm := New()
+	var i interface{}
+	vm.Set("i", i)
+	ret, err := vm.RunString(SCRIPT)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if ret.String() != "null" {
+		t.Fatalf("Expected 'null', got: %v", ret)
+	}
+}
+
+
 /*
 func TestArrayConcatSparse(t *testing.T) {
 function foo(a,b,c)