If you decode a struct which contains a slice of bytes, the returned slice shares the same underlying array with the buffer passed to Decode().
The consequences are:
- If the buffer is later overwritten, the contents of the decoded slice change (see demonstration below).
- If a (potentially large) buffer is no longer in use, the memory underlying array can't be freed as long as there is a reference to the decoded slice of bytes.
I think these consequences aren't intended. It seems better for Decode() to return a copy of the slice of bytes.
package main
import "go.dedis.ch/protobuf"
import "fmt"
func main() {
type foo struct{ Bar []byte }
buf, _ := protobuf.Encode(&foo{[]byte{44, 45}})
var decoded foo
protobuf.Decode(buf, &decoded)
fmt.Println(decoded) // {[44 45]}
buf[len(buf)-1] = 99
fmt.Println(decoded) // {[44 99]}
}
If you decode a struct which contains a slice of bytes, the returned slice shares the same underlying array with the buffer passed to
Decode().The consequences are:
I think these consequences aren't intended. It seems better for
Decode()to return a copy of the slice of bytes.