-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsync.go
66 lines (55 loc) · 1.45 KB
/
sync.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
59
60
61
62
63
64
65
66
package lru
import (
"sync"
"github.com/dboslee/lru/internal"
)
var _ internal.LRU[int, int] = &SyncCache[int, int]{}
// SyncCache is a threadsafe lru cache.
type SyncCache[K comparable, V any] struct {
cache *Cache[K, V]
mu sync.RWMutex
}
// New initializes a new lru cache with the given capacity.
func NewSync[K comparable, V any](options ...CacheOption) *SyncCache[K, V] {
return &SyncCache[K, V]{
cache: New[K, V](options...),
}
}
// Len is the number of key value pairs in the cache.
func (c *SyncCache[K, V]) Len() int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cache.Len()
}
// Set the given key value pair.
// This operation updates the recent usage of the item.
func (c *SyncCache[K, V]) Set(key K, value V) {
c.mu.Lock()
defer c.mu.Unlock()
c.cache.Set(key, value)
}
// Get an item from the cache.
// This operation updates recent usage of the item.
func (c *SyncCache[K, V]) Get(key K) (value V, ok bool) {
c.mu.Lock()
defer c.mu.Unlock()
return c.cache.Get(key)
}
// Peek gets an item from the cache without updating the recent usage.
func (c *SyncCache[K, V]) Peek(key K) (value V, ok bool) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cache.Peek(key)
}
// Delete an item from the cache.
func (c *SyncCache[K, V]) Delete(key K) bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.cache.Delete(key)
}
// Flush deletes all items from the cache.
func (c *SyncCache[K, V]) Flush() {
c.mu.Lock()
defer c.mu.Unlock()
c.cache.Flush()
}