lunixbochs / struc

Better binary packing for Go
MIT License
572 stars 45 forks source link

Custom types of kind 'string' cannot be packed #92

Closed gaba-xyz closed 1 week ago

gaba-xyz commented 1 week ago

Attempting to invoke struc.Pack on a custom type of king string leads to a panic with message: "Cannot resolve size of type: <TYPE NAME>.

Minimal code to reproduce the issue below:

type Foo string

func (*Foo) Pack(p []byte, opt *Options) (int, error) { panic() }
func (*Foo) Unpack(r io.Reader, length int, opt *Options) error { panic() }
func (*Foo) Size(opt *Options) int { return 1 }
func (*Foo) String() string { return "foo" }

type FooWrap struct {
  Foo *Foo `struc:"[1]byte"`
}

var foo *FooWrap
struc.Pack(&w, foo)

I believe the issue stems from the size calculation that is done for fields. The field kind is checked before the check for a custom type which means that the Custom.Size() method is never invoked and the code instead panics.

gaba-xyz commented 1 week ago

I have a tentative fix in my fork, I added a test case as well and looks to me like that has resolved the issue. I would be happy to open a PR if you will accept it. Let me know.

lunixbochs commented 1 week ago

sure, submit a PR