File size: 1,068 Bytes
305487b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package cachex

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
)

type ValueCodec[V any] interface {
	Encode(v V) (string, error)
	Decode(s string) (V, error)
}

type IntCodec struct{}

func (c IntCodec) Encode(v int) (string, error) {
	return strconv.Itoa(v), nil
}

func (c IntCodec) Decode(s string) (int, error) {
	s = strings.TrimSpace(s)
	if s == "" {
		return 0, fmt.Errorf("empty int value")
	}
	return strconv.Atoi(s)
}

type StringCodec struct{}

func (c StringCodec) Encode(v string) (string, error) { return v, nil }
func (c StringCodec) Decode(s string) (string, error) { return s, nil }

type JSONCodec[V any] struct{}

func (c JSONCodec[V]) Encode(v V) (string, error) {
	b, err := json.Marshal(v)
	if err != nil {
		return "", err
	}
	return string(b), nil
}

func (c JSONCodec[V]) Decode(s string) (V, error) {
	var v V
	if strings.TrimSpace(s) == "" {
		return v, fmt.Errorf("empty json value")
	}
	if err := json.Unmarshal([]byte(s), &v); err != nil {
		return v, err
	}
	return v, nil
}