goext/wmo/decoding.go
Mike Schwörer 3a8baaa6d9
All checks were successful
Build Docker and Deploy / Run goext test-suite (push) Successful in 1m45s
v0.0.300 add custom unmarshal-hooks to wmo
2023-11-04 18:55:44 +01:00

78 lines
1.6 KiB
Go

package wmo
import (
"context"
"gogs.mikescher.com/BlackForestBytes/goext/exerr"
)
func (c *Coll[TData]) decodeSingle(ctx context.Context, dec Decodable) (TData, error) {
if c.customDecoder != nil {
res, err := (*c.customDecoder)(ctx, dec)
if err != nil {
return *new(TData), exerr.Wrap(err, "failed to decode single entity with custom-decoder").Type("decoder", *c.customDecoder).Build()
}
for _, hook := range c.unmarshalHooks {
res = hook(res)
}
return res, nil
} else {
var res TData
err := dec.Decode(&res)
if err != nil {
return *new(TData), exerr.Wrap(err, "failed to decode single entity").Type("target-type", res).Build()
}
for _, hook := range c.unmarshalHooks {
res = hook(res)
}
return res, nil
}
}
func (c *Coll[TData]) decodeAll(ctx context.Context, cursor Cursorable) ([]TData, error) {
if c.customDecoder != nil {
res := make([]TData, 0, cursor.RemainingBatchLength())
for cursor.Next(ctx) {
entry, err := (*c.customDecoder)(ctx, cursor)
if err != nil {
return nil, exerr.Wrap(err, "failed to decode entity with custom-decoder").Type("decoder", *c.customDecoder).Build()
}
for _, hook := range c.unmarshalHooks {
entry = hook(entry)
}
res = append(res, entry)
}
return res, nil
} else {
res := make([]TData, 0, cursor.RemainingBatchLength())
err := cursor.All(ctx, &res)
if err != nil {
return nil, exerr.Wrap(err, "failed to batch-decode entity").Type("target-type", res).Build()
}
for i := 0; i < len(res); i++ {
for _, hook := range c.unmarshalHooks {
res[i] = hook(res[i])
}
}
return res, nil
}
}