Debian Codegraph @

common/hmaps/cache.go

raw
1 // Copyright 2026 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hmaps
15
16 import (
17 "sync"
18 )
19
20 // Cache is a simple thread safe cache backed by a map.
21 type Cache[K comparable, T any] struct {
22 m map[K]T
23 opts CacheOptions
24 hasBeenInitialized bool
25 sync.RWMutex
26 }
27
28 // CacheOptions are the options for the Cache.
29 type CacheOptions struct {
30 // If set, the cache will not grow beyond this size.
31 Size uint64
32 }
33
34 var defaultCacheOptions = CacheOptions{}
35
36 // NewCache creates a new Cache with default options.
37 func NewCache[K comparable, T any]() *Cache[K, T] {
38 return &Cache[K, T]{m: make(map[K]T), opts: defaultCacheOptions}
39 }
40
41 // NewCacheWithOptions creates a new Cache with the given options.
42 func NewCacheWithOptions[K comparable, T any](opts CacheOptions) *Cache[K, T] {
43 return &Cache[K, T]{m: make(map[K]T), opts: opts}
44 }
45
46 // Delete deletes the given key from the cache.
47 // If c is nil, this method is a no-op.
48 func (c *Cache[K, T]) Get(key K) (T, bool) {
49 if c == nil {
50 var zero T
51 return zero, false
52 }
53 c.RLock()
54 v, found := c.get(key)
55 c.RUnlock()
56 return v, found
57 }
58
59 func (c *Cache[K, T]) get(key K) (T, bool) {
60 v, found := c.m[key]
61 return v, found
62 }
63
64 // GetOrCreate gets the value for the given key if it exists, or creates it if not.
65 func (c *Cache[K, T]) GetOrCreate(key K, create func() (T, error)) (T, error) {
66 c.RLock()
67 v, found := c.m[key]
68 c.RUnlock()
69 if found {
70 return v, nil
71 }
72 c.Lock()
73 defer c.Unlock()
74 v, found = c.m[key]
75 if found {
76 return v, nil
77 }
78 v, err := create()
79 if err != nil {
80 return v, err
81 }
82 c.clearIfNeeded()
83 c.m[key] = v
84 return v, nil
85 }
86
87 // Contains returns whether the given key exists in the cache.
88 func (c *Cache[K, T]) Contains(key K) bool {
89 c.RLock()
90 _, found := c.m[key]
91 c.RUnlock()
92 return found
93 }
94
95 // InitAndGet initializes the cache if not already done and returns the value for the given key.
96 // The init state will be reset on Reset or Drain.
97 func (c *Cache[K, T]) InitAndGet(key K, init func(get func(key K) (T, bool), set func(key K, value T)) error) (T, error) {
98 var v T
99 c.RLock()
100 if !c.hasBeenInitialized {
101 c.RUnlock()
102 if err := func() error {
103 c.Lock()
104 defer c.Unlock()
105 // Double check in case another goroutine has initialized it in the meantime.
106 if !c.hasBeenInitialized {
107 err := init(c.get, c.set)
108 if err != nil {
109 return err
110 }
111 c.hasBeenInitialized = true
112 }
113 return nil
114 }(); err != nil {
115 return v, err
116 }
117 // Reacquire the read lock.
118 c.RLock()
119 }
120
121 v = c.m[key]
122 c.RUnlock()
123
124 return v, nil
125 }
126
127 // Set sets the given key to the given value.
128 func (c *Cache[K, T]) Set(key K, value T) {
129 c.Lock()
130 c.set(key, value)
131 c.Unlock()
132 }
133
134 // SetIfAbsent sets the given key to the given value if the key does not already exist in the cache.
135 func (c *Cache[K, T]) SetIfAbsent(key K, value T) {
136 c.RLock()
137 if _, found := c.get(key); !found {
138 c.RUnlock()
139 c.Set(key, value)
140 } else {
141 c.RUnlock()
142 }
143 }
144
145 func (c *Cache[K, T]) clearIfNeeded() {
146 if c.opts.Size > 0 && uint64(len(c.m)) >= c.opts.Size {
147 // clear the map
148 clear(c.m)
149 }
150 }
151
152 func (c *Cache[K, T]) set(key K, value T) {
153 c.clearIfNeeded()
154 c.m[key] = value
155 }
156
157 // ForEeach calls the given function for each key/value pair in the cache.
158 // If the function returns false, the iteration stops.
159 func (c *Cache[K, T]) ForEeach(f func(K, T) bool) {
160 c.RLock()
161 defer c.RUnlock()
162 for k, v := range c.m {
163 if !f(k, v) {
164 return
165 }
166 }
167 }
168
169 func (c *Cache[K, T]) Drain() map[K]T {
170 c.Lock()
171 m := c.m
172 c.m = make(map[K]T)
173 c.hasBeenInitialized = false
174 c.Unlock()
175 return m
176 }
177
178 func (c *Cache[K, T]) Len() int {
179 c.RLock()
180 defer c.RUnlock()
181 return len(c.m)
182 }
183
184 func (c *Cache[K, T]) Reset() {
185 c.Lock()
186 clear(c.m)
187 c.hasBeenInitialized = false
188 c.Unlock()
189 }
190
191 // SliceCache is a simple thread safe cache backed by a map.
192 type SliceCache[T any] struct {
193 m map[string][]T
194 sync.RWMutex
195 }
196
197 func NewSliceCache[T any]() *SliceCache[T] {
198 return &SliceCache[T]{m: make(map[string][]T)}
199 }
200
201 func (c *SliceCache[T]) Get(key string) ([]T, bool) {
202 c.RLock()
203 v, found := c.m[key]
204 c.RUnlock()
205 return v, found
206 }
207
208 func (c *SliceCache[T]) Append(key string, values ...T) {
209 c.Lock()
210 c.m[key] = append(c.m[key], values...)
211 c.Unlock()
212 }
213
214 func (c *SliceCache[T]) Reset() {
215 c.Lock()
216 c.m = make(map[string][]T)
217 c.Unlock()
218 }