1
0
mirror of https://github.com/json-iterator/go.git synced 2025-01-08 13:06:29 +02:00

int/float/bool

This commit is contained in:
Tao Wen 2016-12-04 22:15:12 +08:00
parent fafa785306
commit d8153db791
3 changed files with 84 additions and 0 deletions

View File

@ -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() {

View File

@ -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:

View File

@ -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