-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexedlist.go
58 lines (50 loc) · 1.07 KB
/
indexedlist.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// (c) 2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package utils
import (
"container/list"
"sync"
)
type IndexedList interface {
PushFront(key, val interface{})
Exists(key interface{}) bool
}
func NewIndexedList(maxSize int) IndexedList {
if maxSize <= 1 {
maxSize = 1
}
return &indexedList{
entryMap: make(map[interface{}]interface{}),
entryList: new(list.List),
MaxSize: maxSize,
}
}
type indexedList struct {
lock sync.RWMutex
entryMap map[interface{}]interface{}
entryList *list.List
MaxSize int
}
func (c *indexedList) PushFront(key, val interface{}) {
c.lock.Lock()
defer c.lock.Unlock()
if c.exists(key) {
return
}
c.entryList.PushFront(key)
c.entryMap[key] = val
for c.entryList.Len() > c.MaxSize {
e := c.entryList.Back()
c.entryList.Remove(e)
delete(c.entryMap, e.Value)
}
}
func (c *indexedList) Exists(key interface{}) bool {
c.lock.RLock()
defer c.lock.RUnlock()
return c.exists(key)
}
func (c *indexedList) exists(key interface{}) bool {
_, ok := c.entryMap[key]
return ok
}