Support decoding for bool type

This commit is contained in:
Masaaki Goshima 2020-04-22 18:51:42 +09:00
parent 0c42c47179
commit 416d1cf552
2 changed files with 25 additions and 1 deletions

View File

@ -1,6 +1,7 @@
package json package json
import ( import (
"bytes"
"errors" "errors"
"io" "io"
"math" "math"
@ -197,6 +198,8 @@ func (d *Decoder) compile(v reflect.Value) (DecodeOp, error) {
return d.compileUint64() return d.compileUint64()
case reflect.String: case reflect.String:
return d.compileString() return d.compileString()
case reflect.Bool:
return d.compileBool()
} }
return nil, nil return nil, nil
} }
@ -356,6 +359,25 @@ func (d *Decoder) compileString() (DecodeOp, error) {
}, nil }, nil
} }
var (
trueBytes = []byte("true")
falseBytes = []byte("false")
)
func (d *Decoder) compileBool() (DecodeOp, error) {
return func(p uintptr, src []byte, _ []byte) error {
if bytes.Equal(src, trueBytes) {
*(*bool)(unsafe.Pointer(p)) = true
return nil
}
if bytes.Equal(src, falseBytes) {
*(*bool)(unsafe.Pointer(p)) = false
return nil
}
return errors.New("unexpected error bool")
}, nil
}
func (d *Decoder) getTag(field reflect.StructField) string { func (d *Decoder) getTag(field reflect.StructField) string {
return field.Tag.Get("json") return field.Tag.Get("json")
} }

View File

@ -11,9 +11,11 @@ func Test_Decoder(t *testing.T) {
var v struct { var v struct {
A int `json:"abcd"` A int `json:"abcd"`
B string `json:"str"` B string `json:"str"`
C bool
} }
assertErr(t, json.Unmarshal([]byte(`{ "abcd" : 123 , "str" : "hello" }`), &v)) assertErr(t, json.Unmarshal([]byte(`{ "abcd" : 123 , "str" : "hello", "c": true }`), &v))
assertEq(t, "struct.A", 123, v.A) assertEq(t, "struct.A", 123, v.A)
assertEq(t, "struct.B", "hello", v.B) assertEq(t, "struct.B", "hello", v.B)
assertEq(t, "struct.C", true, v.C)
}) })
} }