46 lines
894 B
Go
46 lines
894 B
Go
package cli
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
|
|
"git.maximhutz.com/max/lambda/pkg/codec"
|
|
)
|
|
|
|
type Marshaler interface {
|
|
codec.Marshaler[Repr]
|
|
|
|
InType() string
|
|
}
|
|
|
|
type convertedMarshaler[T any] struct {
|
|
codec codec.Marshaler[T]
|
|
inType string
|
|
}
|
|
|
|
func (c convertedMarshaler[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 convertedMarshaler[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("marshaler for '%s' cannot parse '%s'", allowedType, dataType)
|
|
}
|
|
|
|
return c.codec.Encode(t)
|
|
}
|
|
|
|
func (c convertedMarshaler[T]) InType() string { return c.inType }
|
|
|
|
func ConvertMarshaler[T any](e codec.Marshaler[T], inType string) Marshaler {
|
|
return convertedMarshaler[T]{e, inType}
|
|
}
|