achanda / ipnetwork

A library to work with CIDRs in rust
Apache License 2.0
121 stars 38 forks source link

`NetworkSize` should implement `From<u32>`, `From<u128>`, `TryInto<u32>` and `Into<u128>` #174

Closed ctrlcctrlv closed 1 year ago

ctrlcctrlv commented 1 year ago

I have a PR for this, tracking issue.

achanda commented 1 year ago

What is a usecase for implementing those for NetworkSize?

ctrlcctrlv commented 1 year ago
use ipnetwork::{IpNetwork, NetworkSize};
use std::io::{self, BufRead};

fn main() -> io::Result<()> {
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        let cidr = line?;
        let network = cidr.parse::<IpNetwork>();

        if let Ok(network) = network {
            let first = network.network();
            let last = network.broadcast();
            let size: u128 = match network.size() {
                NetworkSize::V4(v4) => v4 as u128,
                NetworkSize::V6(v6) => v6,
            };

            println!("{}\t{}\t{}", first, last, size);
        } else {
            eprintln!("Invalid IP: {}", cidr);
        }
    }

    Ok(())
}
ctrlcctrlv commented 1 year ago

The above program prints, for example:

[fred@デブ狸 ~/Workspace/cidr]$ cidr
2601::/20
2601::  2601:fff:ffff:ffff:ffff:ffff:ffff:ffff  324518553658426726783156020576256
2601::/8
2600::  26ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 1329227995784915872903807060280344576
0.0.0.0/1
0.0.0.0 127.255.255.255 2147483648
0.0.0.0/8
0.0.0.0 0.255.255.255   16777216
0.0.0.0/63
Invalid IP: 0.0.0.0/63
::/63  
::  ::1:ffff:ffff:ffff:ffff 36893488147419103232
::/127
::  ::1 2
ctrlcctrlv commented 1 year ago

I decided it'd look better to implement Display.

https://github.com/achanda/ipnetwork/pull/175/commits/5c91bd0d7b6f33471bfa98481763184ae8750abd