From 8dbd32faf5c5b4cc125ad3428538f1e1f7ad599d Mon Sep 17 00:00:00 2001 From: David Bimmler Date: Thu, 12 Feb 2026 17:01:00 +0100 Subject: [PATCH] index: make prefix keys use the canonicalized form 10.0.0.100/8 and 10.0.0.0/8 (the canonical form) are equivalent in what IPs they contain. However, the key bytes produced by NetIPPrefix would retain the (arguably garbage) bytes after the relevant prefix. Let's not. Signed-off-by: David Bimmler --- index/netip.go | 2 +- index/netip_test.go | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 index/netip_test.go diff --git a/index/netip.go b/index/netip.go index 7a95f63..f1a5eee 100644 --- a/index/netip.go +++ b/index/netip.go @@ -30,7 +30,7 @@ func NetIPAddrString(s string) (Key, error) { func NetIPPrefix(prefix netip.Prefix) Key { // Use the 16-byte form plus bits to have a constant-size key. - addrBytes := prefix.Addr().As16() + addrBytes := prefix.Masked().Addr().As16() return append(addrBytes[:], uint8(prefix.Bits())) } diff --git a/index/netip_test.go b/index/netip_test.go new file mode 100644 index 0000000..22cd17b --- /dev/null +++ b/index/netip_test.go @@ -0,0 +1,22 @@ +package index + +import ( + "net/netip" + "testing" +) + +func TestNetIPPrefix(t *testing.T) { + k1 := NetIPPrefix(netip.MustParsePrefix("10.0.0.100/8")) + k2 := NetIPPrefix(netip.MustParsePrefix("10.0.0.0/8")) + + if !k1.Equal(k2) { + t.Errorf("expected netip prefix keys to use canonicalized CIDR") + } + + k1s, _ := NetIPPrefixString("10.0.0.100/8") + k2s, _ := NetIPPrefixString("10.0.0.0/8") + + if !k1s.Equal(k2s) { + t.Errorf("expected netip prefix string keys to use canonicalized CIDR") + } +}