Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/runner/hash_map.go
4094 views
1
package runner
2
3
import "sync"
4
5
type hashMap struct {
6
mut sync.RWMutex
7
lookup map[uint64][]Task
8
}
9
10
// newHashMap creates a new hashMap allocated to handle at least size unique
11
// hashes.
12
func newHashMap(size int) *hashMap {
13
return &hashMap{
14
lookup: make(map[uint64][]Task, size),
15
}
16
}
17
18
// Add adds the provided Task into the hashMap. It returns false if t
19
// already exists in the hashMap.
20
func (hm *hashMap) Add(t Task) bool {
21
hm.mut.Lock()
22
defer hm.mut.Unlock()
23
24
hash := t.Hash()
25
for _, compare := range hm.lookup[hash] {
26
if compare.Equals(t) {
27
return false
28
}
29
}
30
31
hm.lookup[hash] = append(hm.lookup[hash], t)
32
return true
33
}
34
35
// Has returns true if t exists in the hashMap.
36
func (hm *hashMap) Has(t Task) bool {
37
hm.mut.RLock()
38
defer hm.mut.RUnlock()
39
40
for _, compare := range hm.lookup[t.Hash()] {
41
if compare.Equals(t) {
42
return true
43
}
44
}
45
46
return false
47
}
48
49
// Delete removes the provided Task from the hashMap. It returns true if the
50
// Task was found and deleted.
51
func (hm *hashMap) Delete(t Task) (deleted bool) {
52
hm.mut.Lock()
53
defer hm.mut.Unlock()
54
55
hash := t.Hash()
56
57
var remaining []Task
58
for _, s := range hm.lookup[hash] {
59
if s.Equals(t) {
60
deleted = true
61
continue
62
}
63
remaining = append(remaining, s)
64
}
65
if len(remaining) == 0 {
66
delete(hm.lookup, hash)
67
} else {
68
hm.lookup[hash] = remaining
69
}
70
71
return deleted
72
}
73
74
// Iterate returns a channel which iterates through all elements in the
75
// hashMap. The channel *must* be fully consumed, otherwise the hashMap will
76
// deadlock.
77
//
78
// The iteration order is not guaranteed.
79
func (hm *hashMap) Iterate() <-chan Task {
80
taskCh := make(chan Task)
81
82
go func() {
83
hm.mut.Lock()
84
defer hm.mut.Unlock()
85
86
for _, set := range hm.lookup {
87
for _, task := range set {
88
taskCh <- task
89
}
90
}
91
92
close(taskCh)
93
}()
94
95
return taskCh
96
}
97
98