Bläddra i källkod

#68 string to float64

Tao Wen 8 år sedan
förälder
incheckning
086001225d
2 ändrade filer med 37 tillägg och 0 borttagningar
  1. 23 0
      extra/fuzzy_decoder.go
  2. 14 0
      extra/fuzzy_decoder_test.go

+ 23 - 0
extra/fuzzy_decoder.go

@@ -15,6 +15,7 @@ const MinInt = -MaxInt - 1
 func RegisterFuzzyDecoders() {
 	jsoniter.RegisterTypeDecoder("string", &FuzzyStringDecoder{})
 	jsoniter.RegisterTypeDecoder("float32", &FuzzyFloat32Decoder{})
+	jsoniter.RegisterTypeDecoder("float64", &FuzzyFloat64Decoder{})
 	jsoniter.RegisterTypeDecoder("int", &FuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
 		if isFloat {
 			val := iter.ReadFloat64()
@@ -201,3 +202,25 @@ func (decoder *FuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.It
 		iter.ReportError("FuzzyFloat32Decoder", "not number or string")
 	}
 }
+
+type FuzzyFloat64Decoder struct {
+}
+
+func (decoder *FuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
+	valueType := iter.WhatIsNext()
+	var str string
+	switch valueType {
+	case jsoniter.Number:
+		*((*float64)(ptr)) = iter.ReadFloat64()
+	case jsoniter.String:
+		str = iter.ReadString()
+		newIter := iter.Config().BorrowIterator([]byte(str))
+		defer iter.Config().ReturnIterator(newIter)
+		*((*float64)(ptr)) = newIter.ReadFloat64()
+		if newIter.Error != nil {
+			iter.Error = newIter.Error
+		}
+	default:
+		iter.ReportError("FuzzyFloat32Decoder", "not number or string")
+	}
+}

+ 14 - 0
extra/fuzzy_decoder_test.go

@@ -71,3 +71,17 @@ func Test_float_to_float32(t *testing.T) {
 	should.Nil(jsoniter.UnmarshalFromString(`1.23`, &val))
 	should.Equal(float32(1.23), val)
 }
+
+func Test_string_to_float64(t *testing.T) {
+	should := require.New(t)
+	var val float64
+	should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
+	should.Equal(float64(100), val)
+}
+
+func Test_float_to_float64(t *testing.T) {
+	should := require.New(t)
+	var val float64
+	should.Nil(jsoniter.UnmarshalFromString(`1.23`, &val))
+	should.Equal(float64(1.23), val)
+}