-
Notifications
You must be signed in to change notification settings - Fork 337
/
binprefix.go
97 lines (77 loc) · 2.58 KB
/
binprefix.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
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package kademlia
import (
"math"
"math/bits"
"github.com/ethersphere/bee/pkg/swarm"
)
// generateCommonBinPrefixes generates the common bin prefixes
// used by the bin balancer.
func generateCommonBinPrefixes(base swarm.Address, suffixLength int) [][]swarm.Address {
bitCombinationsCount := int(math.Pow(2, float64(suffixLength)))
bitSuffixes := make([]uint8, bitCombinationsCount)
for i := 0; i < bitCombinationsCount; i++ {
bitSuffixes[i] = uint8(i)
}
addr := swarm.MustParseHexAddress(base.String())
addrBytes := addr.Bytes()
_ = addrBytes
binPrefixes := make([][]swarm.Address, int(swarm.MaxBins))
// copy base address
for i := range binPrefixes {
binPrefixes[i] = make([]swarm.Address, bitCombinationsCount)
}
for i := range binPrefixes {
for j := range binPrefixes[i] {
pseudoAddrBytes := make([]byte, len(base.Bytes()))
copy(pseudoAddrBytes, base.Bytes())
binPrefixes[i][j] = swarm.NewAddress(pseudoAddrBytes)
}
}
for i := range binPrefixes {
for j := range binPrefixes[i] {
pseudoAddrBytes := binPrefixes[i][j].Bytes()
if len(pseudoAddrBytes) < 1 {
continue
}
// flip first bit for bin
indexByte, posBit := i/8, i%8
if hasBit(bits.Reverse8(pseudoAddrBytes[indexByte]), uint8(posBit)) {
pseudoAddrBytes[indexByte] = bits.Reverse8(clearBit(bits.Reverse8(pseudoAddrBytes[indexByte]), uint8(posBit)))
} else {
pseudoAddrBytes[indexByte] = bits.Reverse8(setBit(bits.Reverse8(pseudoAddrBytes[indexByte]), uint8(posBit)))
}
// set pseudo suffix
bitSuffixPos := suffixLength - 1
for l := i + 1; l < i+suffixLength+1; l++ {
index, pos := l/8, l%8
if hasBit(bitSuffixes[j], uint8(bitSuffixPos)) {
pseudoAddrBytes[index] = bits.Reverse8(setBit(bits.Reverse8(pseudoAddrBytes[index]), uint8(pos)))
} else {
pseudoAddrBytes[index] = bits.Reverse8(clearBit(bits.Reverse8(pseudoAddrBytes[index]), uint8(pos)))
}
bitSuffixPos--
}
// clear rest of the bits
for l := i + suffixLength + 1; l < len(pseudoAddrBytes)*8; l++ {
index, pos := l/8, l%8
pseudoAddrBytes[index] = bits.Reverse8(clearBit(bits.Reverse8(pseudoAddrBytes[index]), uint8(pos)))
}
}
}
return binPrefixes
}
// Clears the bit at pos in n.
func clearBit(n, pos uint8) uint8 {
mask := ^(uint8(1) << pos)
return n & mask
}
// Sets the bit at pos in the integer n.
func setBit(n, pos uint8) uint8 {
return n | 1<<pos
}
func hasBit(n, pos uint8) bool {
return n&(1<<pos) > 0
}