summaryrefslogtreecommitdiff
path: root/lib/containers
diff options
context:
space:
mode:
authorLuke Shumaker <lukeshu@lukeshu.com>2022-07-13 21:44:18 -0600
committerLuke Shumaker <lukeshu@lukeshu.com>2022-07-13 21:44:18 -0600
commit296e9fc0f8812ce0c5684ff99f84e80eef07cd4c (patch)
treef2c0219b5a5db0603af6c55acb6f1684742989fd /lib/containers
parent436e1681c9fcda246c6d84526fc79c87adc7b28d (diff)
Move files to different packages [ci-skip]
Diffstat (limited to 'lib/containers')
-rw-r--r--lib/containers/lru.go77
1 files changed, 77 insertions, 0 deletions
diff --git a/lib/containers/lru.go b/lib/containers/lru.go
new file mode 100644
index 0000000..80f5ff5
--- /dev/null
+++ b/lib/containers/lru.go
@@ -0,0 +1,77 @@
+// Copyright (C) 2022 Luke Shumaker <lukeshu@lukeshu.com>
+//
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+package util
+
+import (
+ "sync"
+
+ lru "github.com/hashicorp/golang-lru"
+)
+
+type LRUCache[K comparable, V any] struct {
+ initOnce sync.Once
+ inner *lru.ARCCache
+}
+
+func (c *LRUCache[K, V]) init() {
+ c.initOnce.Do(func() {
+ c.inner, _ = lru.NewARC(128)
+ })
+}
+
+func (c *LRUCache[K, V]) Add(key K, value V) {
+ c.init()
+ c.inner.Add(key, value)
+}
+func (c *LRUCache[K, V]) Contains(key K) bool {
+ c.init()
+ return c.inner.Contains(key)
+}
+func (c *LRUCache[K, V]) Get(key K) (value V, ok bool) {
+ c.init()
+ _value, ok := c.inner.Get(key)
+ if ok {
+ value = _value.(V)
+ }
+ return value, ok
+}
+func (c *LRUCache[K, V]) Keys() []K {
+ c.init()
+ untyped := c.inner.Keys()
+ typed := make([]K, len(untyped))
+ for i := range untyped {
+ typed[i] = untyped[i].(K)
+ }
+ return typed
+}
+func (c *LRUCache[K, V]) Len() int {
+ c.init()
+ return c.inner.Len()
+}
+func (c *LRUCache[K, V]) Peek(key K) (value V, ok bool) {
+ c.init()
+ _value, ok := c.inner.Peek(key)
+ if ok {
+ value = _value.(V)
+ }
+ return value, ok
+}
+func (c *LRUCache[K, V]) Purge() {
+ c.init()
+ c.inner.Purge()
+}
+func (c *LRUCache[K, V]) Remove(key K) {
+ c.init()
+ c.inner.Remove(key)
+}
+
+func (c *LRUCache[K, V]) GetOrElse(key K, fn func() V) V {
+ var value V
+ var ok bool
+ for value, ok = c.Get(key); !ok; value, ok = c.Get(key) {
+ c.Add(key, fn())
+ }
+ return value
+}