From 416d1cf55250285773e02da6555642c10369ce1e Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Wed, 22 Apr 2020 18:51:42 +0900 Subject: [PATCH] Support decoding for bool type --- decode.go | 22 ++++++++++++++++++++++ decode_test.go | 4 +++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/decode.go b/decode.go index 112516f..5e6ae10 100644 --- a/decode.go +++ b/decode.go @@ -1,6 +1,7 @@ package json import ( + "bytes" "errors" "io" "math" @@ -197,6 +198,8 @@ func (d *Decoder) compile(v reflect.Value) (DecodeOp, error) { return d.compileUint64() case reflect.String: return d.compileString() + case reflect.Bool: + return d.compileBool() } return nil, nil } @@ -356,6 +359,25 @@ func (d *Decoder) compileString() (DecodeOp, error) { }, 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 { return field.Tag.Get("json") } diff --git a/decode_test.go b/decode_test.go index 00e934c..48a2bee 100644 --- a/decode_test.go +++ b/decode_test.go @@ -11,9 +11,11 @@ func Test_Decoder(t *testing.T) { var v struct { A int `json:"abcd"` 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.B", "hello", v.B) + assertEq(t, "struct.C", true, v.C) }) }