-
Notifications
You must be signed in to change notification settings - Fork 10
/
chain.go
100 lines (80 loc) · 1.72 KB
/
chain.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
// Copyright 2017 Tim Oster. All rights reserved.
// Use of this source code is governed by the MIT license.
// More information can be found in the LICENSE file.
package rmnp
import "sync"
type chain struct {
next orderNumber
start *chainLink
length byte
maxLength byte
mutex sync.Mutex
}
type chainLink struct {
next *chainLink
packet *packet
}
func newChain(maxLength byte) *chain {
return &chain{maxLength: maxLength}
}
func (chain *chain) reset() {
chain.mutex.Lock()
defer chain.mutex.Unlock()
chain.next = 0
chain.start = nil
chain.length = 0
}
func (chain *chain) chain(packet *packet) {
chain.mutex.Lock()
defer chain.mutex.Unlock()
if chain.start == nil {
chain.start = &chainLink{next: nil, packet: packet}
} else {
var link *chainLink
for l := chain.start; l != nil; l = l.next {
if greaterThanOrder(packet.order, l.packet.order) {
link = l
} else {
break
}
}
if link == nil {
chain.start = &chainLink{next: chain.start, packet: packet}
} else {
link.next = &chainLink{next: link.next, packet: packet}
}
}
if chain.length >= chain.maxLength {
chain.start = chain.start.next
chain.length--
}
chain.length++
}
func (chain *chain) popConsecutive() *chainLink {
chain.mutex.Lock()
defer chain.mutex.Unlock()
var last *chainLink
for l := chain.start; l != nil; l = l.next {
if l.packet.order == chain.next {
chain.length--
chain.next++
last = l
} else {
break
}
}
if last != nil {
start := chain.start
chain.start = last.next
last.next = nil
return start
}
return nil
}
func (chain *chain) skip() {
chain.mutex.Lock()
defer chain.mutex.Unlock()
if chain.start != nil {
chain.next = chain.start.packet.order
}
}