-
Notifications
You must be signed in to change notification settings - Fork 38
/
datagram_window.go
80 lines (72 loc) · 1.91 KB
/
datagram_window.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
package raknet
import (
"time"
)
// datagramWindow is a queue for incoming datagrams.
type datagramWindow struct {
lowest, highest uint24
queue map[uint24]time.Time
}
// newDatagramWindow returns a new initialised datagram window.
func newDatagramWindow() *datagramWindow {
return &datagramWindow{queue: make(map[uint24]time.Time)}
}
// add puts an index in the window.
func (win *datagramWindow) add(index uint24) bool {
if win.seen(index) {
return false
}
win.highest = max(win.highest, index+1)
win.queue[index] = time.Now()
return true
}
// seen checks if the index passed is known to the datagramWindow.
func (win *datagramWindow) seen(index uint24) bool {
if index < win.lowest {
return true
}
_, ok := win.queue[index]
return ok
}
// shift attempts to delete as many indices from the queue as possible,
// increasing the lowest index if and when possible.
func (win *datagramWindow) shift() (n int) {
var index uint24
for index = win.lowest; index < win.highest; index++ {
if _, ok := win.queue[index]; !ok {
break
}
delete(win.queue, index)
n++
}
win.lowest = index
return n
}
// missing returns a slice of all indices in the datagram queue that weren't
// set using add while within the window of lowest and highest index. The queue
// is shifted after this call.
func (win *datagramWindow) missing(since time.Duration) (indices []uint24) {
missing := false
for index := int(win.highest) - 1; index >= int(win.lowest); index-- {
i := uint24(index)
t, ok := win.queue[i]
if ok {
if time.Since(t) >= since {
// All packets before this one took too long to arrive, so we
// mark them as missing.
missing = true
}
continue
}
if missing {
indices = append(indices, i)
win.queue[i] = time.Time{}
}
}
win.shift()
return indices
}
// size returns the size of the datagramWindow.
func (win *datagramWindow) size() uint24 {
return win.highest - win.lowest
}