-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinker.go
More file actions
90 lines (80 loc) · 1.53 KB
/
linker.go
File metadata and controls
90 lines (80 loc) · 1.53 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
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
81
82
83
84
85
86
87
88
89
90
package blobfs
import (
"errors"
"sync"
)
type linker struct {
store sync.Map
locker sync.RWMutex
}
func newLinker() *linker {
return &linker{
store: sync.Map{},
locker: sync.RWMutex{},
}
}
func (p *linker) Init(blob string) {
p.locker.RLock()
defer p.locker.RUnlock()
_, _ = p.store.LoadOrStore(blob, 0)
}
func (p *linker) Link(blob string) error {
p.locker.RLock()
defer p.locker.RUnlock()
for {
actual, find := p.store.Load(blob)
if !find {
return errors.New("blob not found")
}
if p.store.CompareAndSwap(blob, actual, actual.(int)+1) {
break
}
}
return nil
}
func (p *linker) Unlink(blob string) error {
p.locker.RLock()
defer p.locker.RUnlock()
for {
actual, find := p.store.Load(blob)
if !find {
return errors.New("blob not found")
}
if actual == 0 {
return errors.New("blob is empty")
}
if p.store.CompareAndSwap(blob, actual, actual.(int)-1) {
break
}
}
return nil
}
func (p *linker) Delete(token string) {
p.locker.RLock()
defer p.locker.RUnlock()
p.store.Delete(token)
}
func (p *linker) Gc(item func(key string) error) error {
p.locker.Lock()
defer p.locker.Unlock()
data := make([]string, 0)
p.store.Range(func(k, v interface{}) bool {
if v.(int) == 0 {
data = append(data, k.(string))
}
return true
})
for _, datum := range data {
if err := item(datum); err != nil {
return err
}
p.store.Delete(datum)
}
return nil
}
func (p *linker) Exists(token string) bool {
p.locker.RLock()
defer p.locker.RUnlock()
_, found := p.store.Load(token)
return found
}