Skip to content

SeaweedFS is a distributed storage system for object storage (S3), file systems, Iceberg table buckets, and Lance vector buckets, designed to handle billions of files with O(1) disk access and effortless horizontal scaling.

936 B
Raw Blame
package utils

import (
	"container/list"
)

type CacheEntry struct {
	key   int64
	value []byte
}

type LruCache struct {
	capacity int
	ll       *list.List
	cache    map[int64]*list.Element
}

func NewLRUCache(capacity int) *LruCache {
	return &LruCache{
		capacity: capacity,
		ll:       list.New(),
		cache:    make(map[int64]*list.Element),
	}
}

func (c *LruCache) Get(key int64) ([]byte, bool) {
	if ele, ok := c.cache[key]; ok {
		c.ll.MoveToFront(ele)
		return ele.Value.(*CacheEntry).value, true
	}
	return nil, false
}

func (c *LruCache) Put(key int64, value []byte) {
	if ele, ok := c.cache[key]; ok {
		c.ll.MoveToFront(ele)
		ele.Value.(*CacheEntry).value = value
		return
	}

	if c.ll.Len() >= c.capacity {
		oldest := c.ll.Back()
		if oldest != nil {
			c.ll.Remove(oldest)
			delete(c.cache, oldest.Value.(*CacheEntry).key)
		}
	}

	entry := &CacheEntry{key, value}
	ele := c.ll.PushFront(entry)
	c.cache[key] = ele
}