This repository has been archived by the owner on Nov 30, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
parents.go
104 lines (95 loc) · 1.96 KB
/
parents.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package peter
import (
"secondbit.org/wendy"
"sort"
"sync"
)
type parentMap struct {
*sync.RWMutex
items map[wendy.NodeID][]Topic
}
func newParentMap() *parentMap {
return &parentMap{
new(sync.RWMutex),
map[wendy.NodeID][]Topic{},
}
}
func (p *parentMap) insert(id wendy.NodeID, t Topic) bool {
p.Lock()
defer p.Unlock()
if topics, set := p.items[id]; set {
for _, topic := range topics {
if topic == t {
return false
}
}
p.items[id] = append(p.items[id], t)
} else {
p.items[id] = []Topic{t}
}
return true
}
func (p *parentMap) remove(id wendy.NodeID, t Topic) {
p.Lock()
defer p.Unlock()
if topics, set := p.items[id]; set {
for pos, topic := range topics {
if topic == t {
if len(p.items[id]) == 1 {
p.items[id] = []Topic{}
} else if pos == 0 {
p.items[id] = p.items[id][1:]
} else if pos+1 == len(p.items[id]) {
p.items[id] = p.items[id][:pos]
} else {
p.items[id] = append(p.items[id][:pos], p.items[id][pos+1:]...)
}
return
}
}
}
return
}
func (p *parentMap) topicsByID(id wendy.NodeID) []Topic {
p.RLock()
defer p.RUnlock()
return p.items[id]
}
func (p *parentMap) topics() []Topic {
p.RLock()
defer p.RUnlock()
topics := []Topic{}
for _, t := range p.items {
topics = append(topics, t...)
}
tmpTopics := topicSlice(topics)
sort.Sort(tmpTopics)
topics = []Topic(tmpTopics)
result := []Topic{}
for i, topic := range topics {
if i > 0 && topic == topics[i-1] {
continue
}
result = append(result, topic)
}
return result
}
func (p *parentMap) ids() []wendy.NodeID {
p.RLock()
defer p.RUnlock()
keys := []wendy.NodeID{}
for key, _ := range p.items {
keys = append(keys, key)
}
return keys
}
func (p *parentMap) export() map[wendy.NodeID][]Topic {
output := map[wendy.NodeID][]Topic{}
p.RLock()
defer p.RUnlock()
for id, topics := range p.items {
output[id] = make([]Topic, len(output[id]), (cap(output[id])+1)*2)
copy(output[id], topics)
}
return output
}