forked from libp2p/go-libp2p-kbucket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
72 lines (60 loc) · 1.28 KB
/
main.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
package main
import (
"crypto/sha256"
"encoding/binary"
"fmt"
"os"
"strings"
mh "github.com/multiformats/go-multihash"
)
const bits = 16
const target = 1 << bits
const idLen = 32 + 2
func main() {
pkg := os.Getenv("GOPACKAGE")
file := os.Getenv("GOFILE")
targetFile := strings.TrimSuffix(file, ".go") + "_prefixmap.go"
ids := new([target]uint32)
found := new([target]bool)
count := int32(0)
out := make([]byte, 32)
inp := [idLen]byte{mh.SHA2_256, 32}
hasher := sha256.New()
for i := uint32(0); count < target; i++ {
binary.BigEndian.PutUint32(inp[2:], i)
hasher.Write(inp[:])
out = hasher.Sum(out[:0])
hasher.Reset()
prefix := binary.BigEndian.Uint32(out) >> (32 - bits)
if !found[prefix] {
found[prefix] = true
ids[prefix] = i
count++
}
}
f, err := os.Create(targetFile)
if err != nil {
panic(err)
}
printf := func(s string, args ...interface{}) {
_, err = fmt.Fprintf(f, s, args...)
if err != nil {
panic(err)
}
}
printf("package %s\n\n", pkg)
printf("// Code generated by generate/generate_map.go DO NOT EDIT\n")
printf("var keyPrefixMap = [...]uint32{")
for i, j := range ids[:] {
if i%16 == 0 {
printf("\n\t")
} else {
printf(" ")
}
printf("%d,", j)
}
printf("\n}")
if err = f.Close(); err != nil {
panic(err)
}
}