-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlru.go
More file actions
45 lines (38 loc) · 1.02 KB
/
lru.go
File metadata and controls
45 lines (38 loc) · 1.02 KB
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
package loader
import (
"time"
lru "github.com/hashicorp/golang-lru"
)
// lruWrapper wraps hashicorp's lru cache object, so it's compatible with loader cache
type lruWrapper struct {
*lru.Cache
}
// Add item to cache
func (c lruWrapper) Add(key any, value any) {
c.Cache.Add(key, value)
}
func WithLRU(size int, onEvict ...func(key any, value any)) Option {
var evict func(key any, value any)
if len(onEvict) > 0 {
evict = onEvict[0]
} else if len(onEvict) > 1 {
panic("only one onEvict function is allowed")
}
cache, err := lru.NewWithEvict(size, evict)
if err != nil {
panic(err)
}
return WithDriver(&lruWrapper{cache})
}
func WithARC(size int) Option {
cache, err := lru.NewARC(size)
if err != nil {
panic(err)
}
return WithDriver(cache)
}
// NewLRU is deprecated, use New with WithLRU option instead
func NewLRU[Key comparable, Value any](fn Fetcher[Key, Value], ttl time.Duration, size int, options ...Option) *Loader[Key, Value] {
options = append(options, WithLRU(size))
return New(fn, ttl, options...)
}