Skip to content

Commit

Permalink
codec: add BufferedCodec interface as a codec add-on
Browse files Browse the repository at this point in the history
Codecs may now implement an additional interface, `BufferedCodec`. It
gives codec writers an option to use pre-existing memory when
marshaling messages, if possible.

Implementing the interface is entirely optional, and no changes to
existing codecs are necessary.
  • Loading branch information
HippoBaro committed Sep 10, 2023
1 parent 908fab3 commit bfe6b95
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions encoding/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,43 @@ type Codec interface {
Name() string
}

// SharedBufferPool is a pool of buffers that can be shared, resulting in
// decreased memory allocation.
//
// # Experimental
//
// Notice: This API is EXPERIMENTAL and may be changed or removed in a
// later release.
type SharedBufferPool interface {
// Get returns a buffer with specified length from the pool.
//
// The returned byte slice may be not zero initialized.
//
// Should be thread-safe.
Get(length int) []byte

// Put returns a buffer to the pool.
//
// Should be thread-safe.
Put(*[]byte)
}

// BufferedCodec is an optional interface Codec may implement.
// It signals the ability of the codec to use pre-existing memory
// when writing the wire format of messages.
//
// # Experimental
//
// Notice: This API is EXPERIMENTAL and may be changed or removed in a
// later release.
type BufferedCodec interface {
// MarshalWithBuffer returns the wire format of v.
//
// Implementation may use a buffer from the provided buffer
// pool when marshalling. Doing so enables memory reuse.
MarshalWithBuffer(v any, pool SharedBufferPool) ([]byte, error)
}

var registeredCodecs = make(map[string]Codec)

// RegisterCodec registers the provided Codec for use with all gRPC clients and
Expand Down

0 comments on commit bfe6b95

Please sign in to comment.