Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Oct 24, 2023

Conversation

pilebones
Copy link
Contributor

@pilebones pilebones commented Jul 26, 2022

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.

For example for the annotation below:
```
//msgp:shim uuid.UUID as:[]byte using:uuidToBytes/bytesToUUID
```
When an UUID is an array of bytes (and not a slice of bytes).
We need to use `uuidToBytes()` call and not hardcoded `[]byte()` cast from the generated func `DecodeMsg(dc *msgp.Reader) error`

Ex:
```
func (z *Foobar) 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))
```
Copy link
Collaborator

@klauspost klauspost left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@philhofer philhofer merged commit 4c45222 into tinylib:master Oct 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants