cacheinterface/encoder/binary.go

37 lines
750 B
Go
Raw Normal View History

package encoder
2023-02-05 01:31:09 +00:00
// EncodeValue is a helper that handles conversion of values
// byte slices and strings are converted directly, everything else is marshalled
func EncodeValue(encoder Encoder, val any) ([]byte, error) {
var v []byte
if b, ok := val.([]byte); ok {
v = b
} else if s, ok := val.(string); ok {
b = []byte(s)
} else {
return encoder.Marshal(val)
}
return v, nil
}
2023-02-05 01:31:09 +00:00
// DecodeValue is a helper that handles decoding of values
// byte slices and strings can be assigned directly
func DecodeValue(encoder Encoder, b []byte, v any) error {
switch v := v.(type) {
case *[]byte:
if v != nil {
*v = b
return nil
}
case *string:
if v != nil {
*v = string(b)
return nil
}
}
return encoder.Unmarshal(b, v)
}