package registry import ( "fmt" "reflect" "git.maximhutz.com/max/lambda/pkg/codec" ) type Codec interface { codec.Codec[Expr] InType() string } type convertedCodec[T any] struct { codec codec.Codec[T] inType string } func (c convertedCodec[T]) Decode(s string) (Expr, error) { t, err := c.codec.Decode(s) if err != nil { return nil, err } return NewExpr(c.inType, t), nil } func (c convertedCodec[T]) Encode(r Expr) (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 }