-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathref.go
48 lines (42 loc) · 731 Bytes
/
ref.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
package main
import (
"context"
"sync"
)
type Ref struct {
mu sync.RWMutex
impl *Impl
}
func (ref *Ref) Load(ctx context.Context, configPath string) error {
next, err := LoadImpl(ctx, configPath)
if err != nil {
return err
}
if prev := ref.Swap(next); prev != nil {
if err := prev.Close(); err != nil {
return err
}
}
return nil
}
func (ref *Ref) Close() error {
if prev := ref.Swap(nil); prev != nil {
if err := prev.Close(); err != nil {
return err
}
}
return nil
}
func (ref *Ref) Get() *Impl {
ref.mu.RLock()
impl := ref.impl
ref.mu.RUnlock()
return impl
}
func (ref *Ref) Swap(next *Impl) (prev *Impl) {
ref.mu.Lock()
prev = ref.impl
ref.impl = next
ref.mu.Unlock()
return prev
}