rust-cidr
rust-cidr copied to clipboard
How to get the nth address in a network?
I'm currently using:
fn nth(base: Ipv4Inet, n: usize) -> Option<Ipv4Inet> {
let mut a = base;
// FIXME: This is pointlessly inefficient.
for _ in 0..n {
a = a.next()?;
}
Some(a)
}
How should I do this properly, without iteration?
Hi.
So the next()
implementation actually simply uses the u32
representation (or u128
for IPv6); the code is a bit complicated because I wanted it to be const
, and I made it somewhat generic so it could be used to implement something like your nth
method too - the underlying methods are actually already there, just commented.
I think I didn't expose them yet because I wasn't sure how a proper API for those should look like.
Something like this might do it without const
:
fn nth(base: Ipv4Inet, n: u32) -> Option<Ipv4Inet> {
let result = Ipv4Inet::new(
u32::from(base.address()).checked_add(n)?.into(),
base.network_length(),
).expect("network length was valid before");
if result.network() == base.network() {
Some(result)
} else {
None
}
}
Added new methods in 6f506ca7d12f7798eb4aa662b64c8b0497e8957b and published in 0.2.3