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

proposal: encoding/gob: allow override type marshaling #36353

Open
dsnet opened this issue Jan 1, 2020 · 0 comments
Open

proposal: encoding/gob: allow override type marshaling #36353

dsnet opened this issue Jan 1, 2020 · 0 comments
Labels
Milestone

Comments

@dsnet
Copy link
Member

@dsnet dsnet commented Jan 1, 2020

This is the equivalent change to encoding/gob as what's proposed in #5901 for encoding/json.

I propose adding the following methods:

// RegisterFunc registers a custom encoder to use for specialized types.
// The input f must be a function of the type func(T) ([]byte, error).
//
// When marshaling a value of type R, the function f is called
// if R is identical to T for concrete types or
// if R implements T for interface types.
// Precedence is given to registered encoders that operate on concrete types,
// then registered encoders that operate on interface types
// in the order that they are registered, then the specialized marshal methods
// (i.e., GobEncode or MarshalBinary), and lastly the default behavior of Encode.
//
// It panics if T is already registered or if interface{} is assignable to T.
func (e *Encoder) RegisterFunc(f interface{})

// RegisterFunc registers a custom decoder to use for specialized types.
// The input f must be a function of the type func([]byte, T) error.
//
// When unmarshaling a value of type R, the function f is called
// if R is identical to T for concrete types or
// if R implements T for interface types.
// Precedence is given to registered decoders that operate on concrete types,
// then registered decoders that operate on interface types
// in the order that they are registered, then the specialized unmarshal methods
// (i.e., GobDecode or UnmarshalBinary), and lastly the default behavior of Decode.
//
// It panics if T is already registered or if interface{} is assignable to T.
func (d *Decoder) RegisterFunc(f interface{})

One such use case for this is to make encoding/gob compatible with higher-order Go types containing protobuf messages.

enc := gob.NewEncoder(w)
enc.RegisterFunc(proto.Marshal)
enc.Encode(v)

dec := gob.NewDecoder(r)
dec.RegisterFunc(proto.Unmarshal)
dec.Decode(v)
@gopherbot gopherbot added this to the Proposal milestone Jan 1, 2020
@gopherbot gopherbot added the Proposal label Jan 1, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants
You can’t perform that action at this time.