ipbits_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package ipbits
  2. import (
  3. "net/netip"
  4. "testing"
  5. )
  6. func TestAdd(t *testing.T) {
  7. tests := []struct {
  8. in netip.Addr
  9. x uint64
  10. shift uint
  11. want netip.Addr
  12. }{
  13. {netip.MustParseAddr("10.0.0.1"), 0, 0, netip.MustParseAddr("10.0.0.1")},
  14. {netip.MustParseAddr("10.0.0.1"), 41, 0, netip.MustParseAddr("10.0.0.42")},
  15. {netip.MustParseAddr("10.0.0.1"), 42, 16, netip.MustParseAddr("10.42.0.1")},
  16. {netip.MustParseAddr("10.0.0.1"), 1, 7, netip.MustParseAddr("10.0.0.129")},
  17. {netip.MustParseAddr("10.0.0.1"), 1, 24, netip.MustParseAddr("11.0.0.1")},
  18. {netip.MustParseAddr("2001::1"), 0, 0, netip.MustParseAddr("2001::1")},
  19. {netip.MustParseAddr("2001::1"), 0x41, 0, netip.MustParseAddr("2001::42")},
  20. {netip.MustParseAddr("2001::1"), 1, 7, netip.MustParseAddr("2001::81")},
  21. {netip.MustParseAddr("2001::1"), 0xcafe, 96, netip.MustParseAddr("2001:cafe::1")},
  22. {netip.MustParseAddr("2001::1"), 1, 112, netip.MustParseAddr("2002::1")},
  23. }
  24. for _, tt := range tests {
  25. if got := Add(tt.in, tt.x, tt.shift); tt.want != got {
  26. t.Errorf("%v + (%v << %v) = %v; want %v", tt.in, tt.x, tt.shift, got, tt.want)
  27. }
  28. }
  29. }
  30. func BenchmarkAdd(b *testing.B) {
  31. do := func(b *testing.B, addr netip.Addr) {
  32. b.ReportAllocs()
  33. for i := 0; i < b.N; i++ {
  34. _ = Add(addr, uint64(i), 0)
  35. }
  36. }
  37. b.Run("IPv4", func(b *testing.B) { do(b, netip.IPv4Unspecified()) })
  38. b.Run("IPv6", func(b *testing.B) { do(b, netip.IPv6Unspecified()) })
  39. }
  40. func TestField(t *testing.T) {
  41. tests := []struct {
  42. in netip.Addr
  43. u, v uint
  44. want uint64
  45. }{
  46. {netip.MustParseAddr("1.2.3.4"), 0, 8, 1},
  47. {netip.MustParseAddr("1.2.3.4"), 8, 16, 2},
  48. {netip.MustParseAddr("1.2.3.4"), 16, 24, 3},
  49. {netip.MustParseAddr("1.2.3.4"), 24, 32, 4},
  50. {netip.MustParseAddr("1.2.3.4"), 0, 32, 0x01020304},
  51. {netip.MustParseAddr("1.2.3.4"), 0, 28, 0x102030},
  52. {netip.MustParseAddr("1234:5678:9abc:def0::7654:3210"), 0, 8, 0x12},
  53. {netip.MustParseAddr("1234:5678:9abc:def0::7654:3210"), 8, 16, 0x34},
  54. {netip.MustParseAddr("1234:5678:9abc:def0::7654:3210"), 16, 24, 0x56},
  55. {netip.MustParseAddr("1234:5678:9abc:def0::7654:3210"), 64, 128, 0x76543210},
  56. {netip.MustParseAddr("1234:5678:9abc:def0:beef::7654:3210"), 48, 80, 0xdef0beef},
  57. }
  58. for _, tt := range tests {
  59. if got := Field(tt.in, tt.u, tt.v); got != tt.want {
  60. t.Errorf("Field(%v, %v, %v) = %v (0x%[4]x); want %v (0x%[5]x)", tt.in, tt.u, tt.v, got, tt.want)
  61. }
  62. }
  63. }