From d618d0ded21d763fd56589feecc8674e115bd1f1 Mon Sep 17 00:00:00 2001 From: Dmitriy Matrenichev Date: Fri, 5 Aug 2022 17:42:17 +0300 Subject: [PATCH] chore: no longer treat T and *T as the same types in RegisterEncoderDecoder Ensure MyType{} and &MyType{} are treated as different types. Signed-off-by: Dmitriy Matrenichev --- Makefile | 4 ++-- type_cache.go | 16 ++++++++++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 4c2486a..1d21efe 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # THIS FILE WAS AUTOMATICALLY GENERATED, PLEASE DO NOT EDIT. # -# Generated on 2022-08-03T15:29:15Z by kres latest. +# Generated on 2022-08-05T14:42:43Z by kres latest. # common variables @@ -11,7 +11,7 @@ ARTIFACTS := _out REGISTRY ?= ghcr.io USERNAME ?= siderolabs REGISTRY_AND_USERNAME ?= $(REGISTRY)/$(USERNAME) -GOLANGCILINT_VERSION ?= v1.47.3 +GOLANGCILINT_VERSION ?= v1.48.0 GOFUMPT_VERSION ?= v0.3.1 GO_VERSION ?= 1.19 GOIMPORTS_VERSION ?= v0.1.11 diff --git a/type_cache.go b/type_cache.go index 774f96c..16025ec 100644 --- a/type_cache.go +++ b/type_cache.go @@ -179,13 +179,13 @@ type ( ) // RegisterEncoderDecoder registers the given encoder and decoder for the given type. T should be struct or -// pointer to struct. T and pointer to T are treated the same. +// pointer to struct. func RegisterEncoderDecoder[T any, Enc func(T) ([]byte, error), Dec func([]byte) (T, error)](enc Enc, dec Dec) { var zero T - typ := deref(reflect.TypeOf(zero)) - if typ.Kind() != reflect.Struct { - panic("RegisterEncoderDecoder: T must be a struct") + typ := reflect.TypeOf(zero) + if indirect(typ).Kind() != reflect.Struct { + panic("RegisterEncoderDecoder: T must be struct or pointer to struct") } fnEnc := func(val any) ([]byte, error) { @@ -224,6 +224,14 @@ func RegisterEncoderDecoder[T any, Enc func(T) ([]byte, error), Dec func([]byte) decoders.Add(typ, fnDec) } +func indirect(typ reflect.Type) reflect.Type { + if typ.Kind() == reflect.Ptr { + return typ.Elem() + } + + return typ +} + // CleanEncoderDecoder cleans the map of encoders and decoders. It's not safe to it call concurrently. func CleanEncoderDecoder() { encoders = syncMap[reflect.Type, encoder]{}