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

Comments

@dsnet
Copy link
Member

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
@ianlancetaylor ianlancetaylor added this to Incoming in Proposals (old) Jan 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Incoming
Development

No branches or pull requests

2 participants