-
Notifications
You must be signed in to change notification settings - Fork 16
/
cache.go
61 lines (52 loc) · 1.44 KB
/
cache.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
package machine
import (
"errors"
"sync"
)
// ErrNoExist is returned by the default Cache implementation if a record is not found
var ErrNoExist = errors.New("machine: does not exit")
// Cache is a concurrency safe cache implementation used by Machine.
// A default sync.Map implementation is used if one isn't provided via WithCache
type Cache interface {
// Get get a value by key and an error if one exists
Get(key string) (interface{}, error)
// Range executes the given function on the cache. If the function returns false, the iteration stops.
Range(fn func(k string, val interface{}) bool) error
// Set sets the key and value in the cache
Set(key string, val interface{}) error
// Del deletes the value by key from the map
Del(key string) error
// Close closes the cache
Close() error
}
type cache struct {
data *sync.Map
}
func (c *cache) Get(key string) (interface{}, error) {
val, ok := c.data.Load(key)
if !ok {
return val, ErrNoExist
}
return val, nil
}
func (c *cache) Range(fn func(k string, val interface{}) bool) error {
c.data.Range(func(key, value interface{}) bool {
return fn(key.(string), value)
})
return nil
}
func (c *cache) Set(key string, val interface{}) error {
c.data.Store(key, val)
return nil
}
func (c *cache) Del(key string) error {
c.data.Delete(key)
return nil
}
func (c *cache) Close() error {
c.data.Range(func(key, value interface{}) bool {
c.data.Delete(key)
return true
})
return nil
}