Skip to content

Commit

Permalink
perf: replace the ipv6 map by an array of struct (#20)
Browse files Browse the repository at this point in the history
That replace a 20ms spent in init, with 0.005ms.
  • Loading branch information
Jorropo authored Apr 21, 2022
1 parent 9136dd0 commit af6fa36
Show file tree
Hide file tree
Showing 3 changed files with 79,021 additions and 72,099 deletions.
10 changes: 5 additions & 5 deletions asn.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,14 @@ func (a *asnStore) AsnForIPv6(ip net.IP) (string, error) {
func newAsnStore() (*asnStore, error) {
cr := cidranger.NewPCTrieRanger()

for k, v := range ipv6CidrToAsnMap {
_, nn, err := net.ParseCIDR(k)
for _, v := range ipv6CidrToAsnPairList {
_, nn, err := net.ParseCIDR(v.cidr)
if err != nil {
return nil, fmt.Errorf("failed to parse CIDR %s: %w", k, err)
return nil, fmt.Errorf("failed to parse CIDR %s: %w", v.cidr, err)
}

if err := cr.Insert(&networkWithAsn{*nn, v}); err != nil {
return nil, fmt.Errorf("failed to insert CIDR %s in Trie store: %w", k, err)
if err := cr.Insert(&networkWithAsn{*nn, v.asn}); err != nil {
return nil, fmt.Errorf("failed to insert CIDR %s in Trie store: %w", v.cidr, err)
}
}

Expand Down
12 changes: 6 additions & 6 deletions generate/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (
const (
pkgName = "asnutil"
ipv6OutputFile = "ipv6_asn_map.gen.go"
ipv6MapName = "ipv6CidrToAsnMap"
ipv6listName = "ipv6CidrToAsnPairList"
)

const defaultFile = "https://iptoasn.com/data/ip2asn-v6.tsv.gz"
Expand All @@ -45,10 +45,10 @@ func main() {
panic(err)
}
defer f.Close()
writeMappingToFile(f, ipv6CidrToAsnMap, ipv6MapName)
writeMappingToFile(f, ipv6CidrToAsnMap, ipv6listName)
}

func writeMappingToFile(f *os.File, m map[string]string, mapName string) {
func writeMappingToFile(f *os.File, m map[string]string, listName string) {
printf := func(s string, args ...interface{}) {
_, err := fmt.Fprintf(f, s, args...)
if err != nil {
Expand All @@ -57,11 +57,11 @@ func writeMappingToFile(f *os.File, m map[string]string, mapName string) {
}
printf("package %s\n\n", pkgName)
printf("// Code generated by generate/main.go DO NOT EDIT\n")
printf("var %s = map[string]string {", mapName)
printf("var %s = [...]struct{ cidr, asn string }{", listName)
for k, v := range m {
printf("\n\t \"%s\": \"%s\",", k, v)
printf("\n\t{\"%s\", \"%s\"},", k, v)
}
printf("\n}")
printf("\n}\n")
}

func readMappingFile(path string) map[string]string {
Expand Down
Loading

0 comments on commit af6fa36

Please sign in to comment.