44 lines
915 B
Go
44 lines
915 B
Go
package registry
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.maximhutz.com/max/lambda/pkg/codec"
|
|
)
|
|
|
|
type Conversion interface {
|
|
InType() string
|
|
OutType() string
|
|
|
|
Run(Repr) (Repr, error)
|
|
}
|
|
|
|
type convertedConversion[T, U any] struct {
|
|
conversion codec.Conversion[T, U]
|
|
inType, outType string
|
|
}
|
|
|
|
func (c convertedConversion[T, U]) Run(r Repr) (Repr, error) {
|
|
t, ok := r.Data().(T)
|
|
if !ok {
|
|
return nil, fmt.Errorf("could not parse '%v' as '%s'", t, c.inType)
|
|
}
|
|
|
|
u, err := c.conversion(t)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return NewRepr(c.outType, u), nil
|
|
}
|
|
|
|
func (c convertedConversion[T, U]) InType() string { return c.inType }
|
|
|
|
func (c convertedConversion[T, U]) OutType() string { return c.outType }
|
|
|
|
func RegisterConversion[T, U any](registry *Registry, conversion func(T) (U, error), inType, outType string) error {
|
|
registry.converter.Add(convertedConversion[T, U]{conversion, inType, outType})
|
|
|
|
return nil
|
|
}
|