feat: marshalers to codecs
This commit is contained in:
50
internal/registry/codec.go
Normal file
50
internal/registry/codec.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user