forked from libp2p/go-libp2p-pubsub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
first_seen_cache.go
56 lines (43 loc) · 902 Bytes
/
first_seen_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
package timecache
import (
"context"
"sync"
"time"
)
// FirstSeenCache is a time cache that only marks the expiry of a message when first added.
type FirstSeenCache struct {
lk sync.RWMutex
m map[string]time.Time
ttl time.Duration
done func()
}
var _ TimeCache = (*FirstSeenCache)(nil)
func newFirstSeenCache(ttl time.Duration) *FirstSeenCache {
tc := &FirstSeenCache{
m: make(map[string]time.Time),
ttl: ttl,
}
ctx, done := context.WithCancel(context.Background())
tc.done = done
go background(ctx, &tc.lk, tc.m)
return tc
}
func (tc *FirstSeenCache) Done() {
tc.done()
}
func (tc *FirstSeenCache) Has(s string) bool {
tc.lk.RLock()
defer tc.lk.RUnlock()
_, ok := tc.m[s]
return ok
}
func (tc *FirstSeenCache) Add(s string) bool {
tc.lk.Lock()
defer tc.lk.Unlock()
_, ok := tc.m[s]
if ok {
return false
}
tc.m[s] = time.Now().Add(tc.ttl)
return true
}