diff --git a/jsoniter.go b/jsoniter.go index fb637f5..59c9d95 100644 --- a/jsoniter.go +++ b/jsoniter.go @@ -504,6 +504,33 @@ func (iter *Iterator) readObjectField() (ret string) { return field } +func (iter *Iterator) ReadFloat32() (ret float32) { + str := make([]byte, 0, 10) + for c := iter.readByte(); iter.Error == nil; c = iter.readByte() { + switch c { + case '-', '+', '.', 'e', 'E', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + str = append(str, c) + default: + iter.unreadByte() + val, err := strconv.ParseFloat(string(str), 32) + if err != nil { + iter.Error = err + return + } + return float32(val) + } + } + if iter.Error == io.EOF { + val, err := strconv.ParseFloat(string(str), 32) + if err != nil { + iter.Error = err + return + } + return float32(val) + } + return +} + func (iter *Iterator) ReadFloat64() (ret float64) { str := make([]byte, 0, 10) for c := iter.readByte(); iter.Error == nil; c = iter.readByte() { diff --git a/jsoniter_reflect.go b/jsoniter_reflect.go index 60cbdfb..34c7f4a 100644 --- a/jsoniter_reflect.go +++ b/jsoniter_reflect.go @@ -89,6 +89,27 @@ func (decoder *uint64Decoder) decode(ptr unsafe.Pointer, iter *Iterator) { *((*uint64)(ptr)) = iter.ReadUint64() } +type float32Decoder struct { +} + +func (decoder *float32Decoder) decode(ptr unsafe.Pointer, iter *Iterator) { + *((*float32)(ptr)) = iter.ReadFloat32() +} + +type float64Decoder struct { +} + +func (decoder *float64Decoder) decode(ptr unsafe.Pointer, iter *Iterator) { + *((*float64)(ptr)) = iter.ReadFloat64() +} + +type boolDecoder struct { +} + +func (decoder *boolDecoder) decode(ptr unsafe.Pointer, iter *Iterator) { + *((*bool)(ptr)) = iter.ReadBool() +} + type optionalDecoder struct { valueType reflect.Type valueDecoder Decoder @@ -276,6 +297,12 @@ func decoderOfPtr(type_ reflect.Type) (Decoder, error) { return &uint32Decoder{}, nil case reflect.Uint64: return &uint64Decoder{}, nil + case reflect.Float32: + return &float32Decoder{}, nil + case reflect.Float64: + return &float64Decoder{}, nil + case reflect.Bool: + return &boolDecoder{}, nil case reflect.Struct: return decoderOfStruct(type_) case reflect.Slice: diff --git a/jsoniter_reflect_test.go b/jsoniter_reflect_test.go index c1a2de8..b6c79e8 100644 --- a/jsoniter_reflect_test.go +++ b/jsoniter_reflect_test.go @@ -124,6 +124,36 @@ func Test_reflect_byte(t *testing.T) { } } +func Test_reflect_float32(t *testing.T) { + iter := ParseString(`1.23`) + val := float32(0) + iter.Read(&val) + if val != 1.23 { + fmt.Println(iter.Error) + t.Fatal(val) + } +} + +func Test_reflect_float64(t *testing.T) { + iter := ParseString(`1.23`) + val := float64(0) + iter.Read(&val) + if val != 1.23 { + fmt.Println(iter.Error) + t.Fatal(val) + } +} + +func Test_reflect_bool(t *testing.T) { + iter := ParseString(`true`) + val := false + iter.Read(&val) + if val != true { + fmt.Println(iter.Error) + t.Fatal(val) + } +} + type StructOfString struct { field1 string field2 string