mirror of
https://github.com/daeuniverse/dae.git
synced 2025-07-10 07:48:48 +07:00
optimize(routing): fix slow domain++ ip routing (#133)
This commit is contained in:
@ -5,13 +5,17 @@ package trie
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/mzz2017/softwind/pkg/zeroalloc/buffer"
|
||||
"math/bits"
|
||||
"net/netip"
|
||||
"sort"
|
||||
|
||||
"github.com/daeuniverse/dae/common"
|
||||
"github.com/daeuniverse/dae/common/bitlist"
|
||||
)
|
||||
|
||||
var ValidCidrChars = NewValidChars([]byte{'0', '1'})
|
||||
|
||||
type ValidChars struct {
|
||||
table [256]byte
|
||||
n uint16
|
||||
@ -87,6 +91,47 @@ type Trie struct {
|
||||
chars *ValidChars
|
||||
}
|
||||
|
||||
func Prefix2bin128(prefix netip.Prefix) (bin128 string) {
|
||||
n := prefix.Bits()
|
||||
if n == -1 {
|
||||
panic("! BadPrefix: " + prefix.String())
|
||||
}
|
||||
if prefix.Addr().Is4() {
|
||||
n += 96
|
||||
}
|
||||
ip := prefix.Addr().As16()
|
||||
buf := buffer.NewBuffer(128)
|
||||
defer buf.Put()
|
||||
loop:
|
||||
for i := 0; i < len(ip); i++ {
|
||||
for j := 7; j >= 0; j-- {
|
||||
if (ip[i]>>j)&1 == 1 {
|
||||
_ = buf.WriteByte('1')
|
||||
} else {
|
||||
_ = buf.WriteByte('0')
|
||||
}
|
||||
n--
|
||||
if n == 0 {
|
||||
break loop
|
||||
}
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func NewTrieFromPrefixes(cidrs []netip.Prefix) (*Trie, error) {
|
||||
var keys []string
|
||||
// Convert netip.Prefix -> '0' '1' string
|
||||
for _, prefix := range cidrs {
|
||||
keys = append(keys, Prefix2bin128(prefix))
|
||||
}
|
||||
t, err := NewTrie(keys, ValidCidrChars)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// NewTrie creates a new *Trie struct, from a slice of sorted strings.
|
||||
func NewTrie(keys []string, chars *ValidChars) (*Trie, error) {
|
||||
// Check chars.
|
||||
|
Reference in New Issue
Block a user