feat: marshalers to codecs

This commit is contained in:
2026-02-07 00:36:05 -05:00
parent b61ca744e0
commit 30382bee7e
9 changed files with 79 additions and 107 deletions

View File

@@ -0,0 +1,50 @@
package registry
import (
"fmt"
"reflect"
"git.maximhutz.com/max/lambda/pkg/codec"
)
type Codec interface {
codec.Codec[Repr]
InType() string
}
type convertedCodec[T any] struct {
codec codec.Codec[T]
inType string
}
func (c convertedCodec[T]) Decode(s string) (Repr, error) {
t, err := c.codec.Decode(s)
if err != nil {
return nil, err
}
return NewRepr(c.inType, t), nil
}
func (c convertedCodec[T]) Encode(r Repr) (string, error) {
t, ok := r.Data().(T)
if !ok {
dataType := reflect.TypeOf(r.Data())
allowedType := reflect.TypeFor[T]()
return "", fmt.Errorf("Codec for '%s' cannot parse '%s'", allowedType, dataType)
}
return c.codec.Encode(t)
}
func (c convertedCodec[T]) InType() string { return c.inType }
func RegisterCodec[T any](registry *Registry, m codec.Codec[T], inType string) error {
if _, ok := registry.codecs[inType]; ok {
return fmt.Errorf("Codec for '%s' already registered", inType)
}
registry.codecs[inType] = convertedCodec[T]{m, inType}
return nil
}