forked from maypok86/otter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilder.go
73 lines (59 loc) · 1.39 KB
/
builder.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
package otter
import "errors"
const (
defaultStatsEnabled = false
)
var ErrIllegalCapacity = errors.New("capacity should be positive")
type options[K comparable, V any] struct {
capacity int
statsEnabled bool
costFunc func(key K, value V) uint32
}
func (o *options[K, V]) validate() error {
return nil
}
func (o *options[K, V]) toConfig() Config[K, V] {
return Config[K, V]{
Capacity: o.capacity,
StatsEnabled: o.statsEnabled,
CostFunc: o.costFunc,
}
}
type Builder[K comparable, V any] struct {
options[K, V]
}
func MustBuilder[K comparable, V any](capacity int) *Builder[K, V] {
b, err := NewBuilder[K, V](capacity)
if err != nil {
panic(err)
}
return b
}
func NewBuilder[K comparable, V any](capacity int) (*Builder[K, V], error) {
if capacity <= 0 {
return nil, ErrIllegalCapacity
}
return &Builder[K, V]{
options: options[K, V]{
capacity: capacity,
statsEnabled: defaultStatsEnabled,
costFunc: func(key K, value V) uint32 {
return 1
},
},
}, nil
}
func (b *Builder[K, V]) StatsEnabled(statsEnabled bool) *Builder[K, V] {
b.statsEnabled = statsEnabled
return b
}
func (b *Builder[K, V]) Cost(costFunc func(key K, value V) uint32) *Builder[K, V] {
b.costFunc = costFunc
return b
}
func (b *Builder[K, V]) Build() (*Cache[K, V], error) {
if err := b.validate(); err != nil {
return nil, err
}
return NewCache(b.toConfig()), nil
}