package cache
import (
"hash/fnv"
"sync"
)
func Hash(what []byte) uint64 {
h := fnv.New64()
h.Write(what)
return h.Sum64()
}
type Cache struct {
shards [shardSize]*shard
}
type shard struct {
items map[uint64]interface{}
size int
sync.RWMutex
}
func New(size int) *Cache {
ssize := size / shardSize
if ssize < 4 {
ssize = 4
}
c := &Cache{}
for i := range shardSize {
c.shards[i] = newShard(ssize)
}
return c
}
func (c *Cache) Add(key uint64, el interface{}) bool {
shard := key & (shardSize - 1)
return c.shards[shard].Add(key, el)
}
func (c *Cache) Get(key uint64) (interface{}, bool) {
shard := key & (shardSize - 1)
return c.shards[shard].Get(key)
}
func (c *Cache) Remove(key uint64) {
shard := key & (shardSize - 1)
c.shards[shard].Remove(key)
}
func (c *Cache) Len() int {
l := 0
for _, s := range &c.shards {
l += s.Len()
}
return l
}
func (c *Cache) Walk(f func(map[uint64]interface{}, uint64) bool) {
for _, s := range &c.shards {
s.Walk(f)
}
}
func newShard(size int) *shard { return &shard{items: make(map[uint64]interface{}), size: size} }
func (s *shard) Add(key uint64, el interface{}) bool {
eviction := false
s.Lock()
if len(s.items) >= s.size {
if _, ok := s.items[key]; !ok {
for k := range s.items {
delete(s.items, k)
eviction = true
break
}
}
}
s.items[key] = el
s.Unlock()
return eviction
}
func (s *shard) Remove(key uint64) {
s.Lock()
delete(s.items, key)
s.Unlock()
}
func (s *shard) Evict() {
s.Lock()
for k := range s.items {
delete(s.items, k)
break
}
s.Unlock()
}
func (s *shard) Get(key uint64) (interface{}, bool) {
s.RLock()
el, found := s.items[key]
s.RUnlock()
return el, found
}
func (s *shard) Len() int {
s.RLock()
l := len(s.items)
s.RUnlock()
return l
}
func (s *shard) Walk(f func(map[uint64]interface{}, uint64) bool) {
s.RLock()
items := make([]uint64, len(s.items))
i := 0
for k := range s.items {
items[i] = k
i++
}
s.RUnlock()
for _, k := range items {
s.Lock()
ok := f(s.items, k)
s.Unlock()
if !ok {
return
}
}
}
const shardSize = 256