Files
lambda/internal/cli/conversion.go

68 lines
1.3 KiB
Go

package cli
import (
"fmt"
"git.maximhutz.com/max/lambda/pkg/codec"
)
type Conversion interface {
InType() string
OutType() string
Run(Repr) (Repr, error)
}
type forwardCodec[T, U any] struct {
codec codec.Codec[T, U]
inType, outType string
}
func (c forwardCodec[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.outType)
}
u, err := c.codec.Encode(t)
if err != nil {
return nil, err
}
return NewRepr(c.inType, u), nil
}
func (c forwardCodec[T, U]) InType() string { return c.inType }
func (c forwardCodec[T, U]) OutType() string { return c.outType }
type backwardCodec[T, U any] struct {
codec codec.Codec[T, U]
inType, outType string
}
func (c backwardCodec[T, U]) Run(r Repr) (Repr, error) {
u, ok := r.Data().(U)
if !ok {
return nil, fmt.Errorf("could not parse '%v' as '%s'", r, c.inType)
}
t, err := c.codec.Decode(u)
if err != nil {
return nil, err
}
return NewRepr(c.outType, t), nil
}
func (c backwardCodec[T, U]) InType() string { return c.outType }
func (c backwardCodec[T, U]) OutType() string { return c.inType }
func ConvertCodec[T, U any](e codec.Codec[T, U], inType, outType string) []Conversion {
return []Conversion{
forwardCodec[T, U]{e, inType, outType},
backwardCodec[T, U]{e, inType, outType},
}
}