bouncer/internal/store/redis/helper.go

67 lines
1.0 KiB
Go

package redis
import (
"encoding/json"
"strings"
"github.com/pkg/errors"
)
type jsonWrapper[T any] struct {
value T
}
func (w *jsonWrapper[T]) MarshalBinary() ([]byte, error) {
data, err := json.Marshal(w.value)
if err != nil {
return nil, errors.WithStack(err)
}
return data, nil
}
func (w *jsonWrapper[T]) UnmarshalBinary(data []byte) error {
if err := json.Unmarshal(data, &w.value); err != nil {
return errors.WithStack(err)
}
return nil
}
func (w *jsonWrapper[T]) Value() T {
return w.value
}
func wrap[T any](v T) *jsonWrapper[T] {
return &jsonWrapper[T]{v}
}
func unwrap[T any](v any) (T, error) {
str, ok := v.(string)
if !ok {
return *new(T), errors.Errorf("could not unwrap value of type '%T'", v)
}
u := new(T)
if err := json.Unmarshal([]byte(str), u); err != nil {
return *new(T), errors.WithStack(err)
}
return *u, nil
}
func allNilValues(values []any) bool {
for _, v := range values {
if v != nil {
return false
}
}
return true
}
func key(parts ...string) string {
return strings.Join(parts, ":")
}