-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.go
47 lines (38 loc) · 783 Bytes
/
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
package rest
import (
"fmt"
"reflect"
"sync"
)
type hashcode string
const emptyhash = hashcode("")
type hasher interface {
hash() hashcode
}
type cache struct {
cacheT reflect.Type
items map[hashcode]hasher
mutex sync.RWMutex
}
func makeCache(any interface{}) cache {
ca := cache{}
ca.cacheT = reflect.TypeOf(any)
ca.items = map[hashcode]hasher{}
return ca
}
func (ca *cache) put(h hasher) {
if ht := reflect.TypeOf(h); ht != ca.cacheT {
msg := fmt.Sprintf("Error: expected type %v but received type %v", ca.cacheT, ht)
panic(msg)
}
hsh := h.hash()
ca.mutex.Lock()
defer ca.mutex.Unlock()
ca.items[hsh] = h
}
func (ca *cache) get(hsh hashcode) (hasher, bool) {
ca.mutex.RLock()
defer ca.mutex.RUnlock()
item, ok := ca.items[hsh]
return item, ok
}