Skip to content

Commit

Permalink
chore: no longer treat T and *T as the same types in RegisterEncoderD…
Browse files Browse the repository at this point in the history
…ecoder

Ensure MyType{} and &MyType{} are treated as different types.

Signed-off-by: Dmitriy Matrenichev <dmitry.matrenichev@siderolabs.com>
  • Loading branch information
DmitriyMV committed Aug 5, 2022
1 parent aa7ee6c commit d618d0d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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
Expand Down
16 changes: 12 additions & 4 deletions type_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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]{}
Expand Down

0 comments on commit d618d0d

Please sign in to comment.