ugorji / go

idiomatic codec and rpc lib for msgpack, cbor, json, etc. msgpack.org[Go]
MIT License
1.85k stars 295 forks source link

nils may get encoded as empty structs #329

Closed notnoop closed 4 years ago

notnoop commented 4 years ago

We hit a behavior change related to handling nil map values. Beginning with ffda9d4 , nil map values may be interpreted as a pointer to empty structs instead when going through a roundtrip of encoding and decoding.

Reproduction case

The following test passes on v1.1.4 (until a2a200a ), but fails on v1.1.6 (since ffda9d4):

func TestSerializing_NilMapValues(t *testing.T) {
    type Entry struct{}
    type Entries struct {
        Map map[string]*Entry
    }

    c := Entries{
        Map: map[string]*Entry{
            "nil":   nil,
            "empty": &Entry{},
        },
    }

    msgPackH := &codec.MsgpackHandle{}

    var buf bytes.Buffer
    encoder := codec.NewEncoder(&buf, msgPackH)
    err := encoder.Encode(&c)
    if err != nil {
        t.Fatalf("failed to encode: %v", err)
    }

    var f Entries

    decoder := codec.NewDecoder(&buf, msgPackH)
    err = decoder.Decode(&f)
    if err != nil {
        t.Fatalf("failed to decode: %v", err)
    }

    if !reflect.DeepEqual(c, f) {
        t.Errorf(`roundtrip encoding doesn't match
expected: %v
found:    %v

empty value: %#+v
nil value:   %#+v`, c, f, f.Map["empty"], f.Map["nil"])
    }
}

The failing test output:

$ go test . -run '^TestSerializing_NilMapValues$'
--- FAIL: TestSerializing_NilMapValues (0.00s)
    custom_consul_test.go:42: roundtrip encoding doesn't match
        expected: {map[empty:0x18ea4e0 nil:<nil>]}
        found:    {map[empty:0x18ea4e0 nil:0x18ea4e0]}

        empty value: &main.Entry{}
        nil value:   &main.Entry{}
FAIL
FAIL    github.com/notnoop/ugorji-compatibility 0.056s
FAIL