diff --git a/decode.go b/decode.go index 574f2ed..63ca64f 100644 --- a/decode.go +++ b/decode.go @@ -5,11 +5,13 @@ import "github.com/shamaton/msgpack/v2/internal/decoding" // UnmarshalAsMap decodes data that is encoded as map format. // This is the same thing that StructAsArray sets false. func UnmarshalAsMap(data []byte, v interface{}) error { - return decoding.Decode(data, v, false) + _, err := decoding.Decode(data, v, false, true) + return err } // UnmarshalAsArray decodes data that is encoded as array format. // This is the same thing that StructAsArray sets true. func UnmarshalAsArray(data []byte, v interface{}) error { - return decoding.Decode(data, v, true) + _, err := decoding.Decode(data, v, true, true) + return err } diff --git a/internal/decoding/decoding.go b/internal/decoding/decoding.go index a1b064d..9e62699 100644 --- a/internal/decoding/decoding.go +++ b/internal/decoding/decoding.go @@ -2,6 +2,7 @@ package decoding import ( "fmt" + "io" "reflect" "github.com/shamaton/msgpack/v2/internal/common" @@ -15,27 +16,27 @@ type decoder struct { // Decode analyzes the MessagePack-encoded data and stores // the result into the pointer of v. -func Decode(data []byte, v interface{}, asArray bool) error { +func Decode(data []byte, v interface{}, asArray bool, strictLengthCheck bool) (int, error) { d := decoder{data: data, asArray: asArray} if d.data == nil || len(d.data) < 1 { - return fmt.Errorf("data is empty") + return 0, io.EOF } rv := reflect.ValueOf(v) if rv.Kind() != reflect.Ptr { - return fmt.Errorf("holder must set pointer value. but got: %t", v) + return 0, fmt.Errorf("holder must set pointer value. but got: %t", v) } rv = rv.Elem() last, err := d.decode(rv, 0) if err != nil { - return err + return 0, err } - if len(data) != last { - return fmt.Errorf("failed deserialization size=%d, last=%d", len(data), last) + if strictLengthCheck && len(data) != last { + return 0, fmt.Errorf("failed deserialization size=%d, last=%d", len(data), last) } - return err + return last, err } func (d *decoder) decode(rv reflect.Value, offset int) (int, error) { diff --git a/msgpack.go b/msgpack.go index 0c0bd5d..7651daa 100644 --- a/msgpack.go +++ b/msgpack.go @@ -21,7 +21,8 @@ func Marshal(v interface{}) ([]byte, error) { // Unmarshal analyzes the MessagePack-encoded data and stores // the result into the pointer of v. func Unmarshal(data []byte, v interface{}) error { - return decoding.Decode(data, v, StructAsArray) + _, err := decoding.Decode(data, v, StructAsArray, true) + return err } // AddExtCoder adds encoders for extension types.