pkg/net: add InCIDR to check if an IP is within a CIDR range
This function checks whether an IP address is contained within a CIDR
network. The IP can be provided as a string or byte list, and the CIDR
must be in standard notation (e.g., "192.168.1.0/24").
The parameter order (ip, cidr) allows using this as a validator:
ip: net.InCIDR("10.0.0.0/8")
The original proposal was to add IPInCIDR, but that reads oddly to me,
and InCIDR with the first parameter being "ip" is already intuitive.
Moreover, later on we also want an API to check if one CIDR overlaps
with another CIDR, and CIDROverlapsCIDR is an even weirder name.
Wanting to call that API OverlapsCIDR, use InCIDR here.
This helps DFS's inventory module, which needed to roll its own version
of this function via lots of builtin calls like strings.Split,
math/bits.Rsh, net.ParseIP, and other logic like string interpolation.
│ old │ new │
│ B/op │ B/op vs base │
VetInventory 4.565Gi ± ∞ ¹ 4.322Gi ± ∞ ¹ -5.33% (p=1.000 n=1)
│ old │ new │
│ allocs/op │ allocs/op vs base │
VetInventory 47.29M ± ∞ ¹ 43.96M ± ∞ ¹ -7.04% (p=1.000 n=1)
Fixes #3865.
Signed-off-by: Daniel Martí <mvdan@mvdan.cc>
Change-Id: Iecfe4532d23e9bbaff531eb8ef02a933105da074
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1229759
Reviewed-by: Matthew Sackman <matthew@cue.works>
TryBot-Result: CUEcueckoo <cueckoo@cuelang.org>