Skip to content

Commit cf45b46

Browse files
authored
Merge pull request #49 from Code-Hex/bn-jbowers/main
Add a GetDefault method.
2 parents 5303a9a + ad21351 commit cf45b46

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

cache.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,23 @@ func (c *Cache[K, V]) Get(key K) (zero V, ok bool) {
222222
return item.Value, true
223223
}
224224

225+
// GetOrSet atomically gets a key's value from the cache, or if the
226+
// key is not present, sets the given value.
227+
// The loaded result is true if the value was loaded, false if stored.
228+
func (c *Cache[K, V]) GetOrSet(key K, val V, opts ...ItemOption) (actual V, loaded bool) {
229+
c.mu.Lock()
230+
defer c.mu.Unlock()
231+
item, ok := c.cache.Get(key)
232+
233+
if !ok || item.Expired() {
234+
item := newItem(key, val, opts...)
235+
c.cache.Set(key, item)
236+
return val, false
237+
}
238+
239+
return item.Value, true
240+
}
241+
225242
// DeleteExpired all expired items from the cache.
226243
func (c *Cache[K, V]) DeleteExpired() {
227244
c.mu.Lock()

example_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77

88
cache "github.com/Code-Hex/go-generics-cache"
99
"github.com/Code-Hex/go-generics-cache/policy/lfu"
10+
"github.com/Code-Hex/go-generics-cache/policy/lru"
1011
)
1112

1213
func ExampleCache() {
@@ -143,6 +144,19 @@ func ExampleCache_Contains() {
143144
// false
144145
}
145146

147+
func ExampleCache_GetOrSet() {
148+
c := cache.New(cache.AsLRU[string, int](lru.WithCapacity(10)))
149+
c.Set("a", 1)
150+
151+
val1, ok1 := c.GetOrSet("b", 2)
152+
fmt.Println(val1, ok1)
153+
val2, ok2 := c.GetOrSet("a", 3)
154+
fmt.Println(val2, ok2)
155+
// Output:
156+
// 2 false
157+
// 1 true
158+
}
159+
146160
func ExampleNewNumber() {
147161
nc := cache.NewNumber[string, int]()
148162
nc.Set("a", 1)

0 commit comments

Comments
 (0)