Debian Codegraph @

policy/simple/simple.go

raw symbols SCIP
1 package simple
2
3 import (
4 "sort"
5 "time"
6 )
7
8 // Cache is a simple cache has no clear priority for evict cache.
9 type Cache[K comparable, V any] struct {
10 items map[K]*entry[V]
11 }
12
13 type entry[V any] struct {
14 val V
15 createdAt time.Time
16 }
17
18 // NewCache creates a new non-thread safe cache.
19 func NewCache[K comparable, V any]() *Cache[K, V] {
20 return &Cache[K, V]{
21 items: make(map[K]*entry[V], 0),
22 }
23 }
24
25 // Set sets any item to the cache. replacing any existing item.
26 // The default item never expires.
27 func (c *Cache[K, V]) Set(k K, v V) {
28 c.items[k] = &entry[V]{
29 val: v,
30 createdAt: time.Now(),
31 }
32 }
33
34 // Get gets an item from the cache.
35 // Returns the item or zero value, and a bool indicating whether the key was found.
36 func (c *Cache[K, V]) Get(k K) (val V, ok bool) {
37 got, found := c.items[k]
38 if !found {
39 return
40 }
41 return got.val, true
42 }
43
44 // Keys returns cache keys. the order is sorted by created.
45 func (c *Cache[K, _]) Keys() []K {
46 ret := make([]K, 0, len(c.items))
47 for key := range c.items {
48 ret = append(ret, key)
49 }
50 sort.Slice(ret, func(i, j int) bool {
51 i1 := c.items[ret[i]]
52 i2 := c.items[ret[j]]
53 return i1.createdAt.Before(i2.createdAt)
54 })
55 return ret
56 }
57
58 // Delete deletes the item with provided key from the cache.
59 func (c *Cache[K, V]) Delete(key K) {
60 delete(c.items, key)
61 }
62
63 // Len returns the number of items in the cache.
64 func (c *Cache[K, V]) Len() int {
65 return len(c.items)
66 }