Debian Codegraph @

gopls/internal/util/lru/lru.go

raw symbols SCIP
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // The lru package implements a fixed-size in-memory LRU cache.
6 package lru
7
8 import (
9 "container/heap"
10 "fmt"
11 "sync"
12 )
13
14 // A Cache is a fixed-size in-memory LRU cache, storing values of type V keyed
15 // by keys of type K.
16 type Cache[K comparable, V any] struct {
17 impl *cache
18 }
19
20 // Get retrieves the value for the specified key.
21 // If the key is found, its access time is updated.
22 //
23 // The second result reports whether the key was found.
24 func (c *Cache[K, V]) Get(key K) (V, bool) {
25 v, ok := c.impl.get(key)
26 if !ok {
27 var zero V
28 return zero, false
29 }
30 // Handle untyped nil explicitly to avoid a panic in the type assertion
31 // below.
32 if v == nil {
33 var zero V
34 return zero, true
35 }
36 return v.(V), true
37 }
38
39 // Set stores a value for the specified key, using its given size to update the
40 // current cache size, evicting old entries as necessary to fit in the cache
41 // capacity.
42 //
43 // Size must be a non-negative value. If size is larger than the cache
44 // capacity, the value is not stored and the cache is not modified.
45 func (c *Cache[K, V]) Set(key K, value V, size int) {
46 c.impl.set(key, value, size)
47 }
48
49 // New creates a new Cache with the given capacity, which must be positive.
50 //
51 // The cache capacity uses arbitrary units, which are specified during the Set
52 // operation.
53 func New[K comparable, V any](capacity int) *Cache[K, V] {
54 if capacity == 0 {
55 panic("zero capacity")
56 }
57
58 return &Cache[K, V]{&cache{
59 capacity: capacity,
60 m: make(map[any]*entry),
61 }}
62 }
63
64 // cache is the non-generic implementation of [Cache].
65 //
66 // (Using a generic wrapper around a non-generic impl avoids unnecessary
67 // "stenciling" or code duplication.)
68 type cache struct {
69 capacity int
70
71 mu sync.Mutex
72 used int // used capacity, in user-specified units
73 m map[any]*entry // k/v lookup
74 lru queue // min-atime priority queue of *entry
75 clock int64 // clock time, incremented whenever the cache is updated
76 }
77
78 type entry struct {
79 key any
80 value any
81 size int // caller-specified size
82 atime int64 // last access / set time
83 index int // index of entry in the heap slice
84 }
85
86 func (c *cache) get(key any) (any, bool) {
87 c.mu.Lock()
88 defer c.mu.Unlock()
89
90 c.clock++ // every access updates the clock
91
92 if e, ok := c.m[key]; ok { // cache hit
93 e.atime = c.clock
94 heap.Fix(&c.lru, e.index)
95 return e.value, true
96 }
97
98 return nil, false
99 }
100
101 func (c *cache) set(key, value any, size int) {
102 if size < 0 {
103 panic(fmt.Sprintf("size must be non-negative, got %d", size))
104 }
105 if size > c.capacity {
106 return // uncacheable
107 }
108
109 c.mu.Lock()
110 defer c.mu.Unlock()
111
112 c.clock++
113
114 // Remove the existing cache entry for key, if it exists.
115 e, ok := c.m[key]
116 if ok {
117 c.used -= e.size
118 heap.Remove(&c.lru, e.index)
119 delete(c.m, key)
120 }
121
122 // Evict entries until the new value will fit.
123 newUsed := c.used + size
124 if newUsed < 0 {
125 return // integer overflow; return silently
126 }
127 c.used = newUsed
128 for c.used > c.capacity {
129 // evict oldest entry
130 e = heap.Pop(&c.lru).(*entry)
131 c.used -= e.size
132 delete(c.m, e.key)
133 }
134
135 // Store the new value.
136 // Opt: e is evicted, so it can be reused to reduce allocation.
137 if e == nil {
138 e = new(entry)
139 }
140 e.key = key
141 e.value = value
142 e.size = size
143 e.atime = c.clock
144 c.m[e.key] = e
145 heap.Push(&c.lru, e)
146
147 if len(c.m) != len(c.lru) {
148 panic("map and LRU are inconsistent")
149 }
150 }
151
152 // -- priority queue boilerplate --
153
154 // queue is a min-atime priority queue of cache entries.
155 type queue []*entry
156
157 func (q queue) Len() int { return len(q) }
158
159 func (q queue) Less(i, j int) bool { return q[i].atime < q[j].atime }
160
161 func (q queue) Swap(i, j int) {
162 q[i], q[j] = q[j], q[i]
163 q[i].index = i
164 q[j].index = j
165 }
166
167 func (q *queue) Push(x any) {
168 e := x.(*entry)
169 e.index = len(*q)
170 *q = append(*q, e)
171 }
172
173 func (q *queue) Pop() any {
174 last := len(*q) - 1
175 e := (*q)[last]
176 (*q)[last] = nil // aid GC
177 *q = (*q)[:last]
178 return e
179 }