From 6efada43e73c40e0c76c441f84cf02cc00d3eb1b Mon Sep 17 00:00:00 2001 From: vince Date: Sun, 26 Jul 2020 15:52:29 +0800 Subject: Implement the LRU Cache --- cache/lru_id_cache.go | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 cache/lru_id_cache.go (limited to 'cache/lru_id_cache.go') diff --git a/cache/lru_id_cache.go b/cache/lru_id_cache.go new file mode 100644 index 00000000..e31f2843 --- /dev/null +++ b/cache/lru_id_cache.go @@ -0,0 +1,64 @@ +package cache + +import ( + lru "github.com/hashicorp/golang-lru" + + "github.com/MichaelMure/git-bug/entity" +) + +type LRUIdCache struct { + parentCache *lru.Cache + maxSize int + onEvict func(id entity.Id) +} + +func NewLRUIdCache(size int, onEvicted func(id entity.Id)) (*LRUIdCache, error) { + cache, err := lru.New(size) + if err != nil { + return nil, err + } + + return &LRUIdCache{ + cache, + size, + onEvicted, + }, nil +} + +func (c *LRUIdCache) Add(id entity.Id) bool { + return c.parentCache.Add(id, nil) +} + +func (c *LRUIdCache) Contains(id entity.Id) bool { + return c.parentCache.Contains(id) +} + +func (c *LRUIdCache) Get(id entity.Id) bool { + _, present := c.parentCache.Get(id) + return present +} + +func (c *LRUIdCache) GetOldest() (entity.Id, bool) { + id, _, present := c.parentCache.GetOldest() + return id.(entity.Id), present +} + +func (c *LRUIdCache) GetAll() (ids []entity.Id) { + interfaceKeys := c.parentCache.Keys() + for _, id := range interfaceKeys { + ids = append(ids, id.(entity.Id)) + } + return +} + +func (c *LRUIdCache) Len() int { + return c.parentCache.Len() +} + +func (c *LRUIdCache) Remove(id entity.Id) bool { + return c.parentCache.Remove(id) +} + +func (c *LRUIdCache) Resize(size int) int { + return c.parentCache.Resize(size) +} -- cgit