Functional Weave
Code in Rust

net.cidr-hosts@1.0.0

impl/rust.rs

1,294 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::net_cidr_cidr_info::cidr_info;
use super::net_ipv4::{format_ipv4, parse_ipv4};  ← from net.ipv4 ^1.0.0 · built alongside by fune

/// Every usable host address of an IPv4 block, in order, for a sweep.
///
/// The limit is required, not optional: a typo of /8 for /28 is sixteen
/// million addresses, and the caller should hear about it before allocating
/// them.
///
/// # Panics
/// Panics on a malformed or IPv6 block, a max_count below 1, or a block with
/// more hosts than max_count.
pub fn cidr_hosts(cidr: &str, max_count: i64) -> Vec<String> {
    if max_count < 1 {
        panic!("maxCount must be a whole number of at least 1, received {}", max_count);
    }
    let info = cidr_info(cidr);
    if info.host_count > max_count {
        panic!(
            "{} has {} hosts, more than maxCount {}",
            info.cidr, info.host_count, max_count
        );
    }
    let first = parse_ipv4(&info.first_host);
    (0..info.host_count).map(|i| format_ipv4(first + i)).collect()
}

pub fn fune_vector(args: &[Value]) -> Value {
    let max_count = match &args[1] {
        Value::Int(i) => *i,
        other => panic!("maxCount must be a whole number of at least 1, received {}", other),
    };
    Value::Arr(cidr_hosts(args[0].as_str(), max_count).iter().map(|h| Value::str(h)).collect())
}