-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbucket.go
139 lines (124 loc) · 2.27 KB
/
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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package dht
import (
"container/list"
"fmt"
"math/rand"
"net"
"time"
)
// Bucket manage node
type Bucket struct {
cap int
first *ID
time time.Time
nodes *list.List
}
// NewBucket return a bucket
func NewBucket(first *ID, cap int) *Bucket {
return &Bucket{
cap: cap,
first: first,
time: time.Now(),
nodes: list.New(),
}
}
// Count returns count of all nodes
func (b *Bucket) Count() int {
return b.nodes.Len()
}
// Capacity returns bucket cap
func (b *Bucket) Capacity() int {
return b.cap
}
// Insert a node, move to back if exist node
func (b *Bucket) Insert(id *ID, addr *net.UDPAddr) (n *Node) {
b.handle(func(e *list.Element) bool {
if e.Value.(*Node).id.Compare(id) == 0 {
n = e.Value.(*Node)
b.nodes.MoveToBack(e)
return false
}
return true
})
if n == nil && b.Count() != b.cap {
n = NewNode(id, addr)
b.nodes.PushBack(n)
}
return
}
// Remove a node
func (b *Bucket) Remove(id *ID) {
b.handle(func(e *list.Element) bool {
if e.Value.(*Node).id.Compare(id) == 0 {
b.nodes.Remove(e)
return false
}
return true
})
}
// Find returns node
func (b *Bucket) Find(id *ID) (node *Node) {
b.Map(func(n *Node) bool {
if n.id.Compare(id) == 0 {
node = n
return false
}
return true
})
return
}
// Random returns a random node
func (b *Bucket) Random() *Node {
if b.Count() == 0 {
return nil
}
var node *Node
i := rand.Intn(b.Count())
b.Map(func(n *Node) bool {
if i--; i < 0 {
node = n
return false
}
return true
})
return node
}
// Time returns last contact time
func (b *Bucket) Time() time.Time {
return b.time
}
// Update contact time
func (b *Bucket) Update() {
b.time = time.Now()
}
// Map all node
func (b *Bucket) Map(f func(n *Node) bool) {
b.handle(func(e *list.Element) bool {
return f(e.Value.(*Node))
})
}
func (b *Bucket) handle(f func(e *list.Element) bool) {
for e := b.nodes.Front(); e != nil; e = e.Next() {
if f(e) == false {
return
}
}
}
func (b *Bucket) clean(f func(n *Node) bool) {
e := b.nodes.Front()
for e != nil {
next := e.Next()
if f(e.Value.(*Node)) {
b.nodes.Remove(e)
}
e = next
}
}
func (b *Bucket) String() string {
s := fmt.Sprintf("%v %d\n", b.first, b.Count())
b.Map(func(n *Node) bool {
s += fmt.Sprintf(" %v\n", n)
return true
})
return s
}