-
Notifications
You must be signed in to change notification settings - Fork 75
/
recent.go
51 lines (43 loc) · 1012 Bytes
/
recent.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
package pexlist
import (
"net"
"github.com/cenkalti/rain/internal/tracker"
)
// MaxLength is the maximum number of items to keep in the RecentlySeen list.
const MaxLength = 25
// RecentlySeen is a peer address list that keeps the last `MaxLength` items.
type RecentlySeen struct {
peers []tracker.CompactPeer
offset int
length int
}
// Add a new address to the list.
func (l *RecentlySeen) Add(addr *net.TCPAddr) {
cp := tracker.NewCompactPeer(addr)
if l.has(cp) {
return
}
if l.length >= MaxLength {
l.peers[l.offset] = cp
} else {
l.peers = append(l.peers, cp)
l.length++
}
l.offset = (l.offset + 1) % MaxLength
}
func (l *RecentlySeen) has(cp tracker.CompactPeer) bool {
for _, p := range l.peers {
if p == cp {
return true
}
}
return false
}
// Peers returns the addresses in the list.
func (l *RecentlySeen) Peers() []tracker.CompactPeer {
return l.peers
}
// Len returns the number of addresses in the list.
func (l *RecentlySeen) Len() int {
return len(l.peers)
}