summaryrefslogtreecommitdiff
path: root/pkg/util
diff options
context:
space:
mode:
authorLuke Shumaker <lukeshu@lukeshu.com>2022-07-06 03:05:07 -0600
committerLuke Shumaker <lukeshu@lukeshu.com>2022-07-08 00:15:59 -0600
commitcc09287d752ec6d9c4d4876ab41c4e5859b90f78 (patch)
tree62be91b774959caf88bc160cf5ef6d244c6429c3 /pkg/util
parent5647659f27f8aa18bc10ca4742f8856162325d5c (diff)
Move subvol.go to btrfs/io3_fs.go
Diffstat (limited to 'pkg/util')
-rw-r--r--pkg/util/lru.go73
1 files changed, 73 insertions, 0 deletions
diff --git a/pkg/util/lru.go b/pkg/util/lru.go
new file mode 100644
index 0000000..2b62e69
--- /dev/null
+++ b/pkg/util/lru.go
@@ -0,0 +1,73 @@
+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
+}