Skip to content

Commit

Permalink
fixed GetDefault to be GetOrSet
Browse files Browse the repository at this point in the history
  • Loading branch information
Code-Hex committed Apr 14, 2024
1 parent 40763d5 commit ad21351
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
9 changes: 5 additions & 4 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,20 +222,21 @@ func (c *Cache[K, V]) Get(key K) (zero V, ok bool) {
return item.Value, true
}

// GetDefault atomically gets a key's value from the cache, or if the
// GetOrSet atomically gets a key's value from the cache, or if the
// key is not present, sets the given value.
func (c *Cache[K, V]) GetDefault(key K, val V, opts ...ItemOption) V {
// The loaded result is true if the value was loaded, false if stored.
func (c *Cache[K, V]) GetOrSet(key K, val V, opts ...ItemOption) (actual V, loaded bool) {
c.mu.Lock()
defer c.mu.Unlock()
item, ok := c.cache.Get(key)

if !ok || item.Expired() {
item := newItem(key, val, opts...)
c.cache.Set(key, item)
return val
return val, false
}

return item.Value
return item.Value, true
}

// DeleteExpired all expired items from the cache.
Expand Down
14 changes: 14 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

cache "github.com/Code-Hex/go-generics-cache"
"github.com/Code-Hex/go-generics-cache/policy/lfu"
"github.com/Code-Hex/go-generics-cache/policy/lru"
)

func ExampleCache() {
Expand Down Expand Up @@ -143,6 +144,19 @@ func ExampleCache_Contains() {
// false
}

func ExampleCache_GetOrSet() {
c := cache.New(cache.AsLRU[string, int](lru.WithCapacity(10)))
c.Set("a", 1)

val1, ok1 := c.GetOrSet("b", 2)
fmt.Println(val1, ok1)
val2, ok2 := c.GetOrSet("a", 3)
fmt.Println(val2, ok2)
// Output:
// 2 false
// 1 true
}

func ExampleNewNumber() {
nc := cache.NewNumber[string, int]()
nc.Set("a", 1)
Expand Down

0 comments on commit ad21351

Please sign in to comment.