-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcache.go
61 lines (47 loc) · 801 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package resolver
// basic caching for ad resolver
import (
"github.com/miekg/dns"
"sync"
"time"
)
type entry struct {
msg []dns.RR
secure bool
ttl time.Time
}
type cache struct {
m map[string]*entry
maxN int
sync.RWMutex
}
func newCache(maxN int) (m *cache) {
return &cache{m: make(map[string]*entry), maxN: maxN}
}
func (c *cache) set(key string, item *entry) {
c.Lock()
defer c.Unlock()
if c.maxN == len(c.m) {
for k := range c.m {
delete(c.m, k)
break
}
}
c.m[key] = item
}
func (c *cache) get(key string) (*entry, bool) {
c.RLock()
defer c.RUnlock()
i, ok := c.m[key]
return i, ok
}
func (c *cache) remove(key string) {
c.Lock()
defer c.Unlock()
delete(c.m, key)
}
func (c *cache) len() int {
c.RLock()
defer c.RUnlock()
return len(c.m)
}