codec.go 1015 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package cachex
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. )
  8. type ValueCodec[V any] interface {
  9. Encode(v V) (string, error)
  10. Decode(s string) (V, error)
  11. }
  12. type IntCodec struct{}
  13. func (c IntCodec) Encode(v int) (string, error) {
  14. return strconv.Itoa(v), nil
  15. }
  16. func (c IntCodec) Decode(s string) (int, error) {
  17. s = strings.TrimSpace(s)
  18. if s == "" {
  19. return 0, fmt.Errorf("empty int value")
  20. }
  21. return strconv.Atoi(s)
  22. }
  23. type StringCodec struct{}
  24. func (c StringCodec) Encode(v string) (string, error) { return v, nil }
  25. func (c StringCodec) Decode(s string) (string, error) { return s, nil }
  26. type JSONCodec[V any] struct{}
  27. func (c JSONCodec[V]) Encode(v V) (string, error) {
  28. b, err := json.Marshal(v)
  29. if err != nil {
  30. return "", err
  31. }
  32. return string(b), nil
  33. }
  34. func (c JSONCodec[V]) Decode(s string) (V, error) {
  35. var v V
  36. if strings.TrimSpace(s) == "" {
  37. return v, fmt.Errorf("empty json value")
  38. }
  39. if err := json.Unmarshal([]byte(s), &v); err != nil {
  40. return v, err
  41. }
  42. return v, nil
  43. }