-
Notifications
You must be signed in to change notification settings - Fork 51
/
table.go
84 lines (63 loc) · 1.38 KB
/
table.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
package nat
import (
"net/netip"
"github.com/yaling888/clash/common/generics/list"
)
const (
portBegin = 30000
portLength = 10240
)
var zeroTuple = tuple{}
type tuple struct {
SourceAddr netip.AddrPort
DestinationAddr netip.AddrPort
}
type binding struct {
tuple tuple
offset uint16
}
type table struct {
tuples map[tuple]*list.Element[*binding]
ports [portLength]*list.Element[*binding]
available *list.List[*binding]
}
func (t *table) tupleOf(port uint16) tuple {
offset := port - portBegin
if offset > portLength {
return zeroTuple
}
elm := t.ports[offset]
t.available.MoveToFront(elm)
return elm.Value.tuple
}
func (t *table) portOf(tuple tuple) uint16 {
elm := t.tuples[tuple]
if elm == nil {
return 0
}
t.available.MoveToFront(elm)
return portBegin + elm.Value.offset
}
func (t *table) newConn(tuple tuple) uint16 {
elm := t.available.Back()
b := elm.Value
delete(t.tuples, b.tuple)
t.tuples[tuple] = elm
b.tuple = tuple
t.available.MoveToFront(elm)
return portBegin + b.offset
}
func newTable() *table {
result := &table{
tuples: make(map[tuple]*list.Element[*binding], portLength),
ports: [portLength]*list.Element[*binding]{},
available: list.New[*binding](),
}
for idx := range result.ports {
result.ports[idx] = result.available.PushFront(&binding{
tuple: tuple{},
offset: uint16(idx),
})
}
return result
}