Closed
Description
The MarshalText
and MarshalBinary
methods are a trash factory.
They create a short-lived string that is almost always garbage collectable shortly after creation.
Furthermore, the caller almost always copied the result into another buffer, resulting in further waste.
I propose the addition of the following interfaces to the "encoding" package:
// TextAppender is the interface implemented by an object
// that can append the textual representation of itself.
// If a type implements both [TextAppender] and [TextMarshaler],
// then v.MarshalText() must be semantically identical to v.AppendText(nil).
type TextAppender interface {
// AppendText appends the textual representation of itself to the end of b
// (allocating a larger slice if necessary) and returns the updated slice.
//
// Implementations must not retain b, nor mutate any bytes within b[:len(b)].
AppendText(b []byte) ([]byte, error)
}
type BinaryAppender interface {
AppendBinary([]byte) ([]byte, error)
}
In addition to the above, we would update all types in the stdlib that implement MarshalText
or MarshalBinary
to have the Append
equivalent (and switch the Marshal
implementation to just call the Append
variant). Also, we would teach all stdlib libraries that looks for TextMarshaler
or BinaryMarshaler
to also look for the append (and unmarshal) variant.