-
Notifications
You must be signed in to change notification settings - Fork 53
/
driver.go
59 lines (44 loc) · 1.11 KB
/
driver.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
package driverutil
import (
"context"
"sync"
"github.com/samber/lo"
)
type driver interface{}
type DriverBuilder[D driver] func(ctx context.Context, opts ...Option) (D, error)
type DriverCache[D driver] interface {
Register(name string, builder DriverBuilder[D])
Unregister(name string)
Get(name string) (DriverBuilder[D], bool)
List() []string
}
type driverCache[D driver] struct {
lock sync.Mutex
builders map[string]DriverBuilder[D]
}
func (dc *driverCache[D]) Register(name string, builder DriverBuilder[D]) {
dc.lock.Lock()
defer dc.lock.Unlock()
dc.builders[name] = builder
}
func (dc *driverCache[D]) Unregister(name string) {
dc.lock.Lock()
defer dc.lock.Unlock()
delete(dc.builders, name)
}
func (dc *driverCache[D]) Get(name string) (DriverBuilder[D], bool) {
dc.lock.Lock()
defer dc.lock.Unlock()
builder, ok := dc.builders[name]
return builder, ok
}
func (dc *driverCache[D]) List() []string {
dc.lock.Lock()
defer dc.lock.Unlock()
return lo.Keys(dc.builders)
}
func NewDriverCache[D driver]() DriverCache[D] {
return &driverCache[D]{
builders: make(map[string]DriverBuilder[D]),
}
}