aboutsummaryrefslogtreecommitdiff
path: root/cache/cache.go
diff options
context:
space:
mode:
authorn-peugnet <n.peugnet@free.fr>2021-09-08 18:54:11 +0200
committern-peugnet <n.peugnet@free.fr>2021-09-08 18:54:11 +0200
commit66cb179e0c751c081fbb9ec769a409a7a8115459 (patch)
tree2c3dbdace7f8a36f22b66de5ba929d7f2b5d9da4 /cache/cache.go
parent31432f931012a6cb3ee2c153127e6669a4dbb959 (diff)
downloaddna-backup-66cb179e0c751c081fbb9ec769a409a7a8115459.tar.gz
dna-backup-66cb179e0c751c081fbb9ec769a409a7a8115459.zip
add cache and start using it in repo
Diffstat (limited to 'cache/cache.go')
-rw-r--r--cache/cache.go58
1 files changed, 58 insertions, 0 deletions
diff --git a/cache/cache.go b/cache/cache.go
new file mode 100644
index 0000000..ff2c279
--- /dev/null
+++ b/cache/cache.go
@@ -0,0 +1,58 @@
+package cache
+
+import "sync"
+
+type Cacher interface {
+ Get(key interface{}) (value []byte, exists bool)
+ Set(key interface{}, value []byte)
+ Len() int
+}
+
+type FifoCache struct {
+ head, tail *fifoCacheEntry
+ data map[interface{}][]byte
+ capacity int
+ mutex sync.RWMutex
+}
+
+type fifoCacheEntry struct {
+ Key interface{}
+ Next *fifoCacheEntry
+}
+
+func NewFifoCache(capacity int) *FifoCache {
+ return &FifoCache{data: make(map[interface{}][]byte, capacity), capacity: capacity}
+}
+
+func (c *FifoCache) Get(key interface{}) (value []byte, exists bool) {
+ c.mutex.RLock()
+ defer c.mutex.RUnlock()
+ value, exists = c.data[key]
+ return
+}
+
+func (c *FifoCache) Set(key interface{}, value []byte) {
+ c.mutex.Lock()
+ defer c.mutex.Unlock()
+ if len(c.data) == c.capacity {
+ // Evict first entry
+ evicted := c.head
+ c.head = evicted.Next
+ delete(c.data, evicted.Key)
+ }
+ entry := &fifoCacheEntry{Key: key}
+ if c.head == nil {
+ c.head = entry
+ }
+ if c.tail == nil {
+ c.tail = entry
+ } else {
+ c.tail.Next = entry
+ c.tail = entry
+ }
+ c.data[key] = value
+}
+
+func (c *FifoCache) Len() int {
+ return len(c.data)
+}