tinylib / msgp

A Go code generator for MessagePack / msgpack.org[Go]
MIT License
1.79k stars 190 forks source link

Manage non-[]byte types when type-conversion needed from generated code #312

Closed pilebones closed 11 months ago

pilebones commented 2 years ago

In case of the code below:

package main

import uuid "github.com/gofrs/uuid"

//msgp:shim uuid.UUID as:[]byte using:uuidToBytes/bytesToUUID
type T struct {
    Id uuid.UUID `json:"id"`
}

func uuidToBytes(uid uuid.UUID) []byte {
    return uid[:]
}

func bytesToUUID(uid []byte) uuid.UUID {
    return uuid.FromBytesOrNil(uid)
}

While go generate the tinylib/msgp lib expected type as []byte and doesn't use the function proveded for conversion. See as example the expected generated code as a diff:

func (z *T) DecodeMsg(dc *msgp.Reader) (err error) {
    [...]
    case "Id":
    {
        var zb0002 []byte
-       zb0002, err = dc.ReadBytes([]byte(z.Id))
+       zb0002, err = dc.ReadBytes(uuidToBytes(z.Id))

The representation of the UUID behind github.com/gofrs/uuid is an [16]byte (an array and not a slice of byte). So the actual hardcoded []byte cast not working.

Btw, this bug is only related to the DecodeMsg() func and not to the UnmarshalMsg() func because it reuse well the conversion function provided by the go annotation. That's why the fix is inspired by this second function to correct the first.

This PR allow to fix this kind of issue without crashing existing tests.