From 035f533b62e57490420827163040f432a3ac92b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philipp=20Gille=CC=81?= Date: Tue, 29 Sep 2020 20:43:34 +0200 Subject: [PATCH 1/2] Add constructor for creating a preloaded encoder - Caches schema IDs at the time of encoder creation instead of when the schema ID is required at runtime --- singleencoder.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/singleencoder.go b/singleencoder.go index 4e5394a..0696c63 100644 --- a/singleencoder.go +++ b/singleencoder.go @@ -42,6 +42,31 @@ func NewSingleEncoder(r EncodingRegistry, names *Names) *SingleEncoder { } } +// NewSingleEncoderPreloaded returns a SingleEncoder instance that encodes single +// messages along with their schema identifier and has all required schema IDs cached. +// +// To cache the schema IDs you need to pass objects of the types you plan to marshal later. +// +// Go values unmarshaled through Marshal will have their Avro schemas +// translated with the given Names instance. If names is nil, the global +// namespace will be used. +func NewSingleEncoderPreloaded(ctx context.Context, r EncodingRegistry, names *Names, msgTypes []interface{}) (*SingleEncoder, error) { + if names == nil { + names = globalNames + } + se := &SingleEncoder{ + registry: r, + names: names, + } + for _, msgType := range msgTypes { + x := reflect.New(reflect.TypeOf(msgType)).Elem().Interface() + if err := se.CheckMarshalType(ctx, x); err != nil { + return nil, err + } + } + return se, nil +} + // CheckMarshalType checks that the given type can be marshaled with the encoder. // It also caches any type information obtained from the EncodingRegistry from the // type, so future calls to Marshal with that type won't call it. From 012cd5df8c964480d841d99fcd56afa6bbb48205 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philipp=20Gille=CC=81?= Date: Tue, 13 Oct 2020 15:21:29 +0200 Subject: [PATCH 2/2] Simplify constructor by using the existing one --- singleencoder.go | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/singleencoder.go b/singleencoder.go index 0696c63..8860f75 100644 --- a/singleencoder.go +++ b/singleencoder.go @@ -51,13 +51,7 @@ func NewSingleEncoder(r EncodingRegistry, names *Names) *SingleEncoder { // translated with the given Names instance. If names is nil, the global // namespace will be used. func NewSingleEncoderPreloaded(ctx context.Context, r EncodingRegistry, names *Names, msgTypes []interface{}) (*SingleEncoder, error) { - if names == nil { - names = globalNames - } - se := &SingleEncoder{ - registry: r, - names: names, - } + se := NewSingleEncoder(r, names) for _, msgType := range msgTypes { x := reflect.New(reflect.TypeOf(msgType)).Elem().Interface() if err := se.CheckMarshalType(ctx, x); err != nil {