-
Notifications
You must be signed in to change notification settings - Fork 3
/
gold_stride_test.go
92 lines (81 loc) · 1.98 KB
/
gold_stride_test.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
// Copyright (c) Karl Gaissmaier
// SPDX-License-Identifier: MIT
package bart
import (
"math/rand"
)
// goldStrideTbl, is an 8-bit slow routing table, implemented as a slice
// as a correctness reference.
type goldStrideTbl[V any] []goldStrideItem[V]
type goldStrideItem[V any] struct {
octet byte
bits int
val V
}
// delete prefix
func (t *goldStrideTbl[V]) delete(octet byte, prefixLen int) {
pfx := make([]goldStrideItem[V], 0, len(*t))
for _, e := range *t {
if e.octet == octet && e.bits == prefixLen {
continue
}
pfx = append(pfx, e)
}
*t = pfx
}
// lpm, longest-prefix-match
func (t *goldStrideTbl[V]) lpm(octet byte) (ret V, ok bool) {
const noMatch = -1
longest := noMatch
for _, e := range *t {
if octet&pfxMask(e.bits) == e.octet && e.bits >= longest {
ret = e.val
longest = e.bits
}
}
return ret, longest != noMatch
}
// strideOverlapsPrefix
func (t *goldStrideTbl[V]) strideOverlapsPrefix(octet uint8, prefixLen int) bool {
for _, e := range *t {
minBits := prefixLen
if e.bits < minBits {
minBits = e.bits
}
mask := netMask(minBits)
if octet&mask == e.octet&mask {
return true
}
}
return false
}
// strideOverlaps
func (ta *goldStrideTbl[V]) strideOverlaps(tb *goldStrideTbl[V]) bool {
for _, aItem := range *ta {
for _, bItem := range *tb {
minBits := aItem.bits
if bItem.bits < minBits {
minBits = bItem.bits
}
if aItem.octet&pfxMask(minBits) == bItem.octet&pfxMask(minBits) {
return true
}
}
}
return false
}
func pfxMask(pfxLen int) byte {
return 0xFF << (strideLen - pfxLen)
}
func allStridePfxs() []goldStrideItem[int] {
ret := make([]goldStrideItem[int], 0, maxNodePrefixes-1)
for idx := 1; idx < maxNodePrefixes; idx++ {
octet, bits := idxToPfx(uint(idx))
ret = append(ret, goldStrideItem[int]{octet, bits, idx})
}
return ret
}
func shuffleStridePfxs(pfxs []goldStrideItem[int]) []goldStrideItem[int] {
rand.Shuffle(len(pfxs), func(i, j int) { pfxs[i], pfxs[j] = pfxs[j], pfxs[i] })
return pfxs
}