Debian Codegraph @

expiration.go

raw symbols SCIP
1 package cache
2
3 import (
4 "container/heap"
5 "time"
6 )
7
8 type expirationManager[K comparable] struct {
9 queue expirationQueue[K]
10 mapping map[K]*expirationKey[K]
11 }
12
13 func newExpirationManager[K comparable]() *expirationManager[K] {
14 q := make(expirationQueue[K], 0)
15 heap.Init(&q)
16 return &expirationManager[K]{
17 queue: q,
18 mapping: make(map[K]*expirationKey[K]),
19 }
20 }
21
22 func (m *expirationManager[K]) update(key K, expiration time.Time) {
23 if e, ok := m.mapping[key]; ok {
24 e.expiration = expiration
25 heap.Fix(&m.queue, e.index)
26 } else {
27 v := &expirationKey[K]{
28 key: key,
29 expiration: expiration,
30 }
31 heap.Push(&m.queue, v)
32 m.mapping[key] = v
33 }
34 }
35
36 func (m *expirationManager[K]) len() int {
37 return m.queue.Len()
38 }
39
40 func (m *expirationManager[K]) pop() K {
41 v := heap.Pop(&m.queue)
42 key := v.(*expirationKey[K]).key
43 delete(m.mapping, key)
44 return key
45 }
46
47 func (m *expirationManager[K]) remove(key K) {
48 if e, ok := m.mapping[key]; ok {
49 heap.Remove(&m.queue, e.index)
50 delete(m.mapping, key)
51 }
52 }
53
54 type expirationKey[K comparable] struct {
55 key K
56 expiration time.Time
57 index int
58 }
59
60 // expirationQueue implements heap.Interface and holds CacheItems.
61 type expirationQueue[K comparable] []*expirationKey[K]
62
63 var _ heap.Interface = (*expirationQueue[int])(nil)
64
65 func (pq expirationQueue[K]) Len() int { return len(pq) }
66
67 func (pq expirationQueue[K]) Less(i, j int) bool {
68 // We want Pop to give us the least based on expiration time, not the greater
69 return pq[i].expiration.Before(pq[j].expiration)
70 }
71
72 func (pq expirationQueue[K]) Swap(i, j int) {
73 pq[i], pq[j] = pq[j], pq[i]
74 pq[i].index = i
75 pq[j].index = j
76 }
77
78 func (pq *expirationQueue[K]) Push(x interface{}) {
79 n := len(*pq)
80 item := x.(*expirationKey[K])
81 item.index = n
82 *pq = append(*pq, item)
83 }
84
85 func (pq *expirationQueue[K]) Pop() interface{} {
86 old := *pq
87 n := len(old)
88 item := old[n-1]
89 item.index = -1 // For safety
90 *pq = old[0 : n-1]
91 return item
92 }