Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
const (
looseInterfaceDecodingFlag uint32 = 1 << iota
disallowUnknownFieldsFlag
ignoreMismatchedArrayFieldsFlag
)

const (
Expand Down Expand Up @@ -135,6 +136,16 @@ func (d *Decoder) UseLooseInterfaceDecoding(on bool) {
}
}

// IgnoreMismatchedArrayFields causes the Decoder to ignore mismatch fields number in the
// array and struct.
func (d *Decoder) IgnoreMismatchedArrayFields(on bool) {
if on {
d.flags |= ignoreMismatchedArrayFieldsFlag
} else {
d.flags &= ^ignoreMismatchedArrayFieldsFlag
}
}

// SetCustomStructTag causes the decoder to use the supplied tag as a fallback option
// if there is no msgpack tag.
func (d *Decoder) SetCustomStructTag(tag string) {
Expand Down
8 changes: 6 additions & 2 deletions decode_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,10 +292,14 @@ func decodeStructValue(d *Decoder, v reflect.Value) error {
v.Set(reflect.Zero(v.Type()))
return nil
}

fields := structs.Fields(v.Type(), d.structTag)
if n != len(fields.List) {
return errArrayStruct
if d.flags&ignoreMismatchedArrayFieldsFlag == 0 {
return errArrayStruct
}
if n < len(fields.List) {
fields.List = fields.List[:n]
}
}

for _, f := range fields.List {
Expand Down
64 changes: 64 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,70 @@ func ExampleEncoder_UseArrayEncodedStructs() {
// Output: [foo bar]
}

func ExampleDecoder_IgnoreMismatchedArrayFields() {
type Item struct {
Foo string
Bar string
}
type ItemLong struct {
Foo string
Bar string
Baz string
}

var buf bytes.Buffer

enc := msgpack.NewEncoder(&buf)
enc.UseArrayEncodedStructs(true)

err := enc.Encode(&Item{Foo: "foo", Bar: "bar"})
if err != nil {
panic(err)
}

dec := msgpack.NewDecoder(&buf)
dec.IgnoreMismatchedArrayFields(true)
var itemLong ItemLong
err = dec.Decode(&itemLong)
if err != nil {
panic(err)
}
fmt.Println(itemLong)
// Output: {foo bar }
}

func ExampleDecoder_IgnoreMismatchedArrayFields2() {
type Item struct {
Foo string
Bar string
}
type ItemLong struct {
Foo string
Bar string
Baz string
}

var buf bytes.Buffer

enc := msgpack.NewEncoder(&buf)
enc.UseArrayEncodedStructs(true)

err := enc.Encode(&ItemLong{Foo: "foo", Bar: "bar", Baz: "baz"})
if err != nil {
panic(err)
}

dec := msgpack.NewDecoder(&buf)
dec.IgnoreMismatchedArrayFields(true)
var item Item
err = dec.Decode(&item)
if err != nil {
panic(err)
}
fmt.Println(item)
// Output: {foo bar}
}

func ExampleMarshal_asArray() {
type Item struct {
_msgpack struct{} `msgpack:",as_array"`
Expand Down