github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/net/trie/cidr/cidr_test.go (about) 1 package cidr 2 3 import ( 4 "net" 5 "net/netip" 6 "testing" 7 8 "github.com/Asutorufa/yuhaiin/pkg/utils/assert" 9 ) 10 11 func TestCidrMatch(t *testing.T) { 12 cidrMatch := NewCidrMapper[string]() 13 assert.NoError(t, cidrMatch.Insert("10.2.2.1/18", "testIPv4")) 14 assert.NoError(t, cidrMatch.Insert("2001:0db8:0000:0000:1234:0000:0000:9abc/32", "testIPv6")) 15 assert.NoError(t, cidrMatch.Insert("127.0.0.1/8", "testlocal")) 16 assert.NoError(t, cidrMatch.Insert("ff::/16", "testV6local")) 17 18 search := func(s string) string { 19 res, _ := cidrMatch.Search(s) 20 return res 21 } 22 23 testIPv4 := "10.2.2.1" 24 testIPv4b := "100.2.2.1" 25 testIPv6 := "2001:0db8:0000:0000:1234:0000:0000:9abc" 26 testIPv6b := "3001:0db8:0000:0000:1234:0000:0000:9abc" 27 28 assert.Equal(t, "testIPv4", search(testIPv4)) 29 assert.Equal(t, "testIPv6", search(testIPv6)) 30 assert.Equal(t, "testlocal", search("127.1.1.1")) 31 assert.Equal(t, "", search("129.1.1.1")) 32 assert.Equal(t, "testV6local", search("ff:ff::")) 33 assert.Equal(t, "", search(testIPv4b)) 34 assert.Equal(t, "", search(testIPv6b)) 35 } 36 37 // BenchmarkCidrMatch_Search-4 40390761 25.77 ns/op 16 B/op 1 allocs/op 38 func BenchmarkCidrMatch_Search(b *testing.B) { 39 cidrMatch := NewCidrMapper[string]() 40 assert.NoError(b, cidrMatch.Insert("10.2.2.1/18", "testIPv4")) 41 assert.NoError(b, cidrMatch.Insert("2001:0db8:0000:0000:1234:0000:0000:9abc/32", "testIPv6")) 42 43 testIPv4 := "10.2.2.1" 44 //testIPv4b := "100.2.2.1" 45 //testIPv6 := "2001:0db8:0000:0000:1234:0000:0000:9abc" 46 // testIPv6b := "3001:0db8:0000:0000:1234:0000:0000:9abc" 47 48 b.RunParallel(func(p *testing.PB) { 49 for p.Next() { 50 cidrMatch.Search(testIPv4) 51 // cidrMatch.Search(testIPv6b) 52 } 53 }) 54 } 55 56 func TestXxx(t *testing.T) { 57 _, z, err := net.ParseCIDR("10.0.2.1/24") 58 assert.NoError(t, err) 59 t.Log(z.Mask.Size()) 60 t.Log(z.IP.To4()) 61 62 zz, err := netip.ParsePrefix("10.0.2.1/24") 63 assert.NoError(t, err) 64 t.Log(zz.Bits()) 65 t.Log(zz.Addr().AsSlice()) 66 }