-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
bucket.go
57 lines (48 loc) · 1009 Bytes
/
bucket.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
package dht
import (
"iter"
"maps"
"time"
"github.com/anacrolix/chansync"
"github.com/anacrolix/dht/v2/int160"
)
type bucket struct {
// Per the "Routing Table" section of BEP 5.
changed chansync.BroadcastCond
lastChanged time.Time
nodes map[*node]struct{}
}
func (b *bucket) Len() int {
return len(b.nodes)
}
func (b *bucket) NodeIter() iter.Seq[*node] {
return maps.Keys(b.nodes)
}
// Returns true if f returns true for all nodes. Iteration stops if f returns false.
func (b *bucket) EachNode(f func(*node) bool) bool {
for n := range b.NodeIter() {
if !f(n) {
return false
}
}
return true
}
func (b *bucket) AddNode(n *node, k int) {
if _, ok := b.nodes[n]; ok {
return
}
if b.nodes == nil {
b.nodes = make(map[*node]struct{}, k)
}
b.nodes[n] = struct{}{}
b.lastChanged = time.Now()
b.changed.Broadcast()
}
func (b *bucket) GetNode(addr Addr, id int160.T) *node {
for n := range b.nodes {
if n.hasAddrAndID(addr, id) {
return n
}
}
return nil
}