rust-cidr icon indicating copy to clipboard operation
rust-cidr copied to clipboard

How to get the nth address in a network?

Open fadedbee opened this issue 9 months ago • 1 comments

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?

fadedbee avatar Apr 30 '24 15:04 fadedbee

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
    }
}

stbuehler avatar Apr 30 '24 16:04 stbuehler

Added new methods in 6f506ca7d12f7798eb4aa662b64c8b0497e8957b and published in 0.2.3

stbuehler avatar Jun 25 '24 14:06 stbuehler