neo-go/pkg/core/cache/cache.go

75 lines
1.4 KiB
Go
Raw Normal View History

2020-06-05 09:11:22 +00:00
package cache
2019-11-08 15:40:21 +00:00
import (
"container/list"
"sync"
"github.com/nspcc-dev/neo-go/pkg/util"
2019-11-08 15:40:21 +00:00
)
2020-06-05 09:11:22 +00:00
// HashCache is a payload cache which is used to store
2019-11-08 15:40:21 +00:00
// last consensus payloads.
2020-06-05 09:11:22 +00:00
type HashCache struct {
2019-11-08 15:40:21 +00:00
*sync.RWMutex
maxCap int
elems map[util.Uint256]*list.Element
queue *list.List
}
2020-06-05 09:11:22 +00:00
// Hashable is a type of items which can be stored in the HashCache.
type Hashable interface {
2019-11-15 10:32:40 +00:00
Hash() util.Uint256
}
2020-06-05 09:11:22 +00:00
// NewFIFOCache returns new FIFO cache with the specified capacity.
func NewFIFOCache(capacity int) *HashCache {
return &HashCache{
2019-11-08 15:40:21 +00:00
RWMutex: new(sync.RWMutex),
maxCap: capacity,
elems: make(map[util.Uint256]*list.Element),
queue: list.New(),
}
}
// Add adds payload into a cache if it doesn't already exist.
2020-06-05 09:11:22 +00:00
func (c *HashCache) Add(p Hashable) {
2019-11-08 15:40:21 +00:00
c.Lock()
defer c.Unlock()
h := p.Hash()
if c.elems[h] != nil {
return
}
if c.queue.Len() >= c.maxCap {
first := c.queue.Front()
c.queue.Remove(first)
2020-06-05 09:11:22 +00:00
delete(c.elems, first.Value.(Hashable).Hash())
2019-11-08 15:40:21 +00:00
}
e := c.queue.PushBack(p)
c.elems[h] = e
}
2019-11-15 10:32:40 +00:00
// Has checks if an item is already in cache.
2020-06-05 09:11:22 +00:00
func (c *HashCache) Has(h util.Uint256) bool {
2019-11-15 10:32:40 +00:00
c.RLock()
defer c.RUnlock()
return c.elems[h] != nil
}
2019-11-08 15:40:21 +00:00
// Get returns payload with the specified hash from cache.
2020-06-05 09:11:22 +00:00
func (c *HashCache) Get(h util.Uint256) Hashable {
2019-11-08 15:40:21 +00:00
c.RLock()
defer c.RUnlock()
e, ok := c.elems[h]
if !ok {
2020-06-05 09:11:22 +00:00
return Hashable(nil)
2019-11-08 15:40:21 +00:00
}
2020-06-05 09:11:22 +00:00
return e.Value.(Hashable)
2019-11-08 15:40:21 +00:00
}