Selaa lähdekoodia

fix #195 when decode float as int, report it clearly

Tao Wen 8 vuotta sitten
vanhempi
commit
9f088cbcc4
4 muutettua tiedostoa jossa 19 lisäystä ja 3 poistoa
  1. 1 1
      feature_iter.go
  2. 10 0
      feature_iter_int.go
  3. 6 0
      jsoniter_int_test.go
  4. 2 2
      jsoniter_interface_test.go

+ 1 - 1
feature_iter.go

@@ -168,7 +168,7 @@ func (iter *Iterator) isObjectEnd() bool {
 	if c == '}' {
 		return true
 	}
-	iter.ReportError("isObjectEnd", "object ended prematurely, unexpected char " + string([]byte{c}))
+	iter.ReportError("isObjectEnd", "object ended prematurely, unexpected char "+string([]byte{c}))
 	return true
 }
 

+ 10 - 0
feature_iter_int.go

@@ -113,6 +113,11 @@ func (iter *Iterator) ReadUint32() (ret uint32) {
 }
 
 func (iter *Iterator) readUint32(c byte) (ret uint32) {
+	defer func() {
+		if iter.buf[iter.head] == '.' {
+			iter.ReportError("readUint32", "can not decode float as int")
+		}
+	}()
 	ind := intDigits[c]
 	if ind == 0 {
 		return 0 // single zero
@@ -224,6 +229,11 @@ func (iter *Iterator) ReadUint64() uint64 {
 }
 
 func (iter *Iterator) readUint64(c byte) (ret uint64) {
+	defer func() {
+		if iter.buf[iter.head] == '.' {
+			iter.ReportError("readUint64", "can not decode float as int")
+		}
+	}()
 	ind := intDigits[c]
 	if ind == 0 {
 		return 0 // single zero

+ 6 - 0
jsoniter_int_test.go

@@ -530,6 +530,12 @@ func Test_null_as_number(t *testing.T) {
 	should.Equal("", string(v2))
 }
 
+func Test_float_as_int(t *testing.T) {
+	should := require.New(t)
+	var i int
+	should.NotNil(Unmarshal([]byte(`1.1`), &i))
+}
+
 func Benchmark_jsoniter_encode_int(b *testing.B) {
 	stream := NewStream(ConfigDefault, ioutil.Discard, 64)
 	for n := 0; n < b.N; n++ {

+ 2 - 2
jsoniter_interface_test.go

@@ -13,10 +13,10 @@ import (
 func Test_write_empty_interface_via_placeholder(t *testing.T) {
 	fmt.Println(^uint(0) >> 1)
 	should := require.New(t)
-	m := map[uint32]interface{}{1:"hello"}
+	m := map[uint32]interface{}{1: "hello"}
 	inf := reflect.ValueOf(m).MapIndex(reflect.ValueOf(uint32(1))).Interface()
 	encoder := &placeholderEncoder{
-		cfg: ConfigFastest.(*frozenConfig),
+		cfg:      ConfigFastest.(*frozenConfig),
 		cacheKey: reflect.TypeOf(m).Elem(),
 	}
 	stream := ConfigFastest.BorrowStream(nil)