Skip to content

Commit

Permalink
ipcidr direct using go4.org/netipx
Browse files Browse the repository at this point in the history
  • Loading branch information
wwqgtxx committed Jan 11, 2024
1 parent 3c95a7f commit b15027e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 22 deletions.
36 changes: 16 additions & 20 deletions rule/ipcidr_tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,13 @@ package rules

import (
C "github.com/metacubex/mihomo/constant"

"github.com/kentik/patricia"
tree "github.com/kentik/patricia/generics_tree"
"go4.org/netipx"
"net/netip"
)

type IpCidrTree struct {
IPCIDR // for C.Rule interface
treeV4 *tree.TreeV4[struct{}]
treeV6 *tree.TreeV6[struct{}]
ipSet *netipx.IPSet
ruleCount int
}

Expand All @@ -30,26 +28,26 @@ func (i *IpCidrTree) Match(metadata *C.Metadata) (bool, string) {
if !ip.IsValid() {
return false, ""
}
found := false
if ip.Is4() {
v4 := patricia.NewIPv4AddressFromBytes(ip.AsSlice(), 32)
found, _ = i.treeV4.FindDeepestTag(v4)
} else {
v6 := patricia.NewIPv6Address(ip.AsSlice(), 128)
found, _ = i.treeV6.FindDeepestTag(v6)
if i.ipSet == nil {
return false, ""
}
if i.ipSet.Contains(ip) {
return true, i.adapter
}
return found, i.adapter
return false, ""
}

func (i *IpCidrTree) Insert(ipCidr string) error {
v4, v6, err := patricia.ParseIPFromString(ipCidr)
prefix, err := netip.ParsePrefix(ipCidr)
if err != nil {
return err
}
if v4 != nil {
_, _ = i.treeV4.Set(*v4, struct{}{})
} else {
_, _ = i.treeV6.Set(*v6, struct{}{})
var b netipx.IPSetBuilder
b.AddSet(i.ipSet)
b.AddPrefix(prefix)
i.ipSet, err = b.IPSet()
if err != nil {
return err
}
i.ruleCount++
return nil
Expand All @@ -60,8 +58,6 @@ func (i *IpCidrTree) FinishInsert() {}
func NewIPCIDRTree() *IpCidrTree {
return &IpCidrTree{
IPCIDR: IPCIDR{},
treeV4: tree.NewTreeV4[struct{}](),
treeV6: tree.NewTreeV6[struct{}](),
ruleCount: 0,
}
}
4 changes: 2 additions & 2 deletions rule/ipcidr_tree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func TestIpv4AddFail(t *testing.T) {
assert.IsType(t, errors.New(""), err)

err = tree.Insert("2.2.2.2")
assert.IsType(t, nil, err)
assert.IsType(t, errors.New(""), err)
}

func match(tree *IpCidrTree, ip string) bool {
Expand Down Expand Up @@ -78,7 +78,7 @@ func TestIpv6AddFail(t *testing.T) {
assert.IsType(t, errors.New(""), err)

err = tree.Insert("2001:0fa3:25de::cade")
assert.IsType(t, nil, err)
assert.IsType(t, errors.New(""), err)
}

func TestIpv6Match(t *testing.T) {
Expand Down

0 comments on commit b15027e

Please sign in to comment.