/
utils.go
113 lines (79 loc) · 2.07 KB
/
utils.go
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package onecache
import (
"bytes"
"encoding/gob"
"strconv"
"time"
)
//Helper method to check if an item is expired.
//Current usecase for this is for garbage collection
func (i *Item) IsExpired() bool {
return time.Now().After(i.ExpiresAt)
}
type Serializer interface {
Serialize(i interface{}) ([]byte, error)
DeSerialize(data []byte, i interface{}) error
}
func NewCacheSerializer() *CacheSerializer {
return &CacheSerializer{}
}
//Helper to serialize and deserialize types
type CacheSerializer struct {
}
//Convert a given type into a byte array
//Caveat -> Types you create might have to be registered with the encoding/gob package
func (b *CacheSerializer) Serialize(i interface{}) ([]byte, error) {
if b, ok := i.([]byte); ok {
return b, nil
}
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
if err := enc.Encode(i); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
//Writes a byte array into a type.
func (b *CacheSerializer) DeSerialize(data []byte, i interface{}) error {
if b, ok := i.(*[]byte); ok {
*b = data
return nil
}
return gob.NewDecoder(bytes.NewBuffer(data)).Decode(i)
}
//Increment increases the value of an item by the specified number of steps
func Increment(val interface{}, steps int) (interface{}, error) {
var ret interface{}
switch val.(type) {
case int:
ret = val.(int) + steps
case int32:
ret = val.(int32) + int32(steps)
case int64:
ret = val.(int64) + int64(steps)
case uint:
ret = val.(uint) + uint(steps)
case uint8:
ret = val.(uint8) + uint8(steps)
case uint16:
ret = val.(uint16) + uint16(steps)
case uint32:
ret = val.(uint32) + uint32(steps)
case uint64:
ret = val.(uint64) + uint64(steps)
case string:
num, err := strconv.Atoi(val.(string))
if err != nil {
return -0, err
}
num += steps
ret = strconv.Itoa(num)
default:
return -0, ErrCacheDataCannotBeIncreasedOrDecreased
}
return ret, nil
}
//Decrement decreases the value of an item by the specified number of steps
func Decrement(val interface{}, steps int) (interface{}, error) {
return Increment(val, steps*-1)
}