feat: marshalers to codecs
This commit is contained in:
@@ -13,18 +13,18 @@ type Conversion interface {
|
||||
Run(Repr) (Repr, error)
|
||||
}
|
||||
|
||||
type forwardCodec[T, U any] struct {
|
||||
codec codec.Codec[T, U]
|
||||
type convertedConversion[T, U any] struct {
|
||||
conversion codec.Conversion[T, U]
|
||||
inType, outType string
|
||||
}
|
||||
|
||||
func (c forwardCodec[T, U]) Run(r Repr) (Repr, error) {
|
||||
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.codec.Encode(t)
|
||||
u, err := c.conversion(t)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -32,36 +32,12 @@ func (c forwardCodec[T, U]) Run(r Repr) (Repr, error) {
|
||||
return NewRepr(c.outType, u), nil
|
||||
}
|
||||
|
||||
func (c forwardCodec[T, U]) InType() string { return c.inType }
|
||||
func (c convertedConversion[T, U]) InType() string { return c.inType }
|
||||
|
||||
func (c forwardCodec[T, U]) OutType() string { return c.outType }
|
||||
func (c convertedConversion[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.outType)
|
||||
}
|
||||
|
||||
t, err := c.codec.Decode(u)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return NewRepr(c.inType, t), nil
|
||||
}
|
||||
|
||||
func (c backwardCodec[T, U]) InType() string { return c.outType }
|
||||
|
||||
func (c backwardCodec[T, U]) OutType() string { return c.inType }
|
||||
|
||||
func RegisterCodec[T, U any](registry *Registry, c codec.Codec[T, U], inType, outType string) error {
|
||||
registry.converter.Add(forwardCodec[T, U]{c, inType, outType})
|
||||
registry.converter.Add(backwardCodec[T, U]{c, inType, 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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user