From 95bfc8c5499493e5dd87bcbd87629e4dc48c6473 Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Fri, 21 Aug 2020 11:07:55 +0900 Subject: [PATCH] Add validation for null value --- encode.go | 4 ++++ encode_vm.go | 22 +++++++++++++++++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/encode.go b/encode.go index f41114e..58f019a 100644 --- a/encode.go +++ b/encode.go @@ -148,6 +148,10 @@ func (e *Encoder) encodeForMarshal(v interface{}) ([]byte, error) { } func (e *Encoder) encode(v interface{}) error { + if v == nil { + e.encodeNull() + return nil + } header := (*interfaceHeader)(unsafe.Pointer(&v)) typ := header.typ diff --git a/encode_vm.go b/encode_vm.go index e2d0971..a18cf5d 100644 --- a/encode_vm.go +++ b/encode_vm.go @@ -148,7 +148,9 @@ func (e *Encoder) run(code *opcode) error { ptr := code.ptr isPtr := code.typ.Kind() == reflect.Ptr p := unsafe.Pointer(ptr) - if isPtr && *(*unsafe.Pointer)(p) == nil { + if p == nil { + e.encodeNull() + } else if isPtr && *(*unsafe.Pointer)(p) == nil { e.encodeBytes([]byte{'"', '"'}) } else { if isPtr && code.typ.Elem().Implements(marshalTextType) { @@ -1027,7 +1029,14 @@ func (e *Encoder) run(code *opcode) error { typ: code.typ, ptr: unsafe.Pointer(ptr), })) - b, err := v.(Marshaler).MarshalJSON() + marshaler, ok := v.(Marshaler) + if !ok { + // invalid marshaler + e.encodeNull() + code = field.end + break + } + b, err := marshaler.MarshalJSON() if err != nil { return &MarshalerError{ Type: rtype2type(code.typ), @@ -1099,7 +1108,14 @@ func (e *Encoder) run(code *opcode) error { typ: code.typ, ptr: unsafe.Pointer(ptr), })) - bytes, err := v.(encoding.TextMarshaler).MarshalText() + marshaler, ok := v.(encoding.TextMarshaler) + if !ok { + // invalid marshaler + e.encodeNull() + code = field.end + break + } + bytes, err := marshaler.MarshalText() if err != nil { return &MarshalerError{ Type: rtype2type(code.typ),