-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoptions.go
80 lines (67 loc) · 1.6 KB
/
options.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package evcache
import (
"time"
"github.com/mgnsk/evcache/v4/internal/backend"
)
// Available cache eviction policies.
const (
// FIFO policy orders records in FIFO order.
FIFO = backend.FIFO
// LFU policy orders records in LFU order.
LFU = backend.LFU
// LRU policy orders records in LRU order.
LRU = backend.LRU
)
// Option is a cache configuration option.
type Option interface {
apply(*cacheOptions)
}
type cacheOptions struct {
policy string
capacity int
ttl time.Duration
debounce time.Duration
}
func newDefaultCacheOptions() cacheOptions {
return cacheOptions{
policy: FIFO,
capacity: 0,
ttl: 0,
debounce: 1 * time.Second,
}
}
// WithCapacity option configures the cache with specified capacity.
//
// The zero values configures unbounded capacity.
func WithCapacity(capacity int) Option {
return funcOption(func(opts *cacheOptions) {
opts.capacity = capacity
})
}
// WithPolicy option configures the cache with specified eviction policy.
//
// The zero value configures the FIFO policy.
func WithPolicy(policy string) Option {
return funcOption(func(opts *cacheOptions) {
switch policy {
case "":
opts.policy = FIFO
case FIFO, LRU, LFU:
opts.policy = policy
default:
panic("evcache: invalid eviction policy '" + policy + "'")
}
})
}
// WithTTL option configures the cache with specified default TTL.
//
// The zero value configures infinite default TTL.
func WithTTL(ttl time.Duration) Option {
return funcOption(func(opts *cacheOptions) {
opts.ttl = ttl
})
}
type funcOption func(*cacheOptions)
func (o funcOption) apply(opts *cacheOptions) {
o(opts)
}