| 1 |
package s3fifo |
| 2 |
|
| 3 |
import "container/list" |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
type ghost[K comparable] struct { |
| 9 |
size int |
| 10 |
ll *list.List |
| 11 |
items map[K]*list.Element |
| 12 |
} |
| 13 |
|
| 14 |
func newGhost[K comparable](size int) *ghost[K] { |
| 15 |
return &ghost[K]{ |
| 16 |
size: size, |
| 17 |
ll: list.New(), |
| 18 |
items: make(map[K]*list.Element), |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
func (b *ghost[K]) add(key K) { |
| 23 |
if _, ok := b.items[key]; ok { |
| 24 |
return |
| 25 |
} |
| 26 |
|
| 27 |
for b.ll.Len() >= b.size { |
| 28 |
e := b.ll.Back() |
| 29 |
delete(b.items, e.Value.(K)) |
| 30 |
b.ll.Remove(e) |
| 31 |
} |
| 32 |
|
| 33 |
e := b.ll.PushFront(key) |
| 34 |
b.items[key] = e |
| 35 |
} |
| 36 |
|
| 37 |
func (b *ghost[K]) remove(key K) { |
| 38 |
if e, ok := b.items[key]; ok { |
| 39 |
b.ll.Remove(e) |
| 40 |
delete(b.items, key) |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
func (b *ghost[K]) contains(key K) bool { |
| 45 |
_, ok := b.items[key] |
| 46 |
return ok |
| 47 |
} |
| 48 |
|
| 49 |
func (b *ghost[K]) clear() { |
| 50 |
b.ll.Init() |
| 51 |
for k := range b.items { |
| 52 |
delete(b.items, k) |
| 53 |
} |
| 54 |
} |