Skip to content

Commit

Permalink
add getorset
Browse files Browse the repository at this point in the history
  • Loading branch information
KyleSanderson authored Nov 24, 2024
1 parent be6bef5 commit 6b2ca65
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 10 deletions.
22 changes: 12 additions & 10 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,17 +159,19 @@ func (c *upgradereq) getAllTorrents() (*timeentry, error) {
}

getOrInitialize := func() ttlcache.Item[*timeentry] {
if it, ok := torrentmap.GetItem(set); ok {
if c.CacheBypass == 0 {
it, ok := torrentmap.GetOrSetItem(set, &timeentry{}, ttlcache.DefaultTTL)
if !ok {
return torrentmap.SetItem(set, &timeentry{}, ttlcache.DefaultTTL)
}

if c.CacheBypass == 0 {
return it
} else if c.CacheBypass == 1 {
val := it.GetValue()
val.m.RLock()
defer val.m.RUnlock()
if val.e == nil {
return it
} else if c.CacheBypass == 1 {
val := it.GetValue()
val.m.RLock()
defer val.m.RUnlock()

if val.e == nil {
return it
}
}
}

Expand Down
8 changes: 8 additions & 0 deletions pkg/ttlcache/internal.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ func (c *Cache[K, V]) set(key K, it Item[V]) Item[V] {
return it
}

func (c *Cache[K, V]) getOrSet(key K, it Item[V]) (Item[V], bool) {
if v, ok := c.get(key); ok {
return v, ok
}

return c.set(key, it), true
}

func (c *Cache[K, V]) delete(key K, reason DeallocationReason) {
var v Item[V]
c.l.Lock()
Expand Down
22 changes: 22 additions & 0 deletions pkg/ttlcache/ttlcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,28 @@ func (c *Cache[K, V]) GetItem(key K) (Item[V], bool) {
return it, ok
}

func (c *Cache[K, V]) GetOrSet(key K, value V, duration time.Duration) (V, bool) {
it, ok := c.GetOrSetItem(key, value, duration)
if !ok {
return *new(V), ok
}

return it.GetValue(), ok
}

func (c *Cache[K, V]) GetOrSetItem(key K, value V, duration time.Duration) (Item[V], bool) {
if c.o.defaultTTL == NoTTL && duration == DefaultTTL {
duration = NoTTL
}

it, ok := c.getOrSet(key, Item[V]{v: value, d: duration})
if !ok {
return Item[V]{}, ok
}

return it, ok
}

func (c *Cache[K, V]) Set(key K, value V, duration time.Duration) bool {
c.SetItem(key, value, duration)
return true
Expand Down

0 comments on commit 6b2ca65

Please sign in to comment.