lunixbochs / struc

Better binary packing for Go
MIT License
564 stars 42 forks source link

Chaining Pack() Custom, with struc.Pack() #85

Closed abourget closed 4 years ago

abourget commented 4 years ago

Since struc.Pack() doesn't return the number of written bytes, it's not easy to implement the Pack(...) (int, error) Custom method, that requires the number of written bytes, when that implementation calls struc.Pack() to pack some subelements of a struct.

Is there a better way ?

My initial issue is I have a struct like:

type BaseVariant struct {
    Type Varuint16
    Impl interface{}
}

and I'd like Impl to sort of rescan if the interface{} is a struct, or an interface that would implement the Packer or Custom interfaces, but when I pack that struct, I get an error.

If that can be solved, then I don't need a custom packer that triggered my issue above!

lunixbochs commented 4 years ago

You should be able to call struc.Sizeof() to get the size that will be written.

abourget commented 4 years ago

yeah.. I would have liked to avoid that, for performance reasons.. since it will actually need to do a full packing in order to gauge its size, so it would run the algos twice.. that's the only way?

abourget commented 4 years ago

Would it be complex to have struc handle an interface{} in a field, as if it were calling struc.Pack() on it automatically?

Would you be open to such a contribution?

abourget commented 4 years ago

thanks!