I have a library for a list of IP ranges which are fixed strings and are in the format of Ipv4Net to produce a IpRange struct. I can use once cell Lazy to initialise this once, but this is at runtime.
I want to move this to compile time as the data is fixed and does not change and this will reduce the overhead if any item is in the wrong format or for reasons is unable to be converted. I have tests, but just in case there is any difference in behaviour. I can create a constant for a vector of strings and also a vector of Ipv4Net struct types. I am unable to create IpRange struct as this seems to initialise using "new" and I would need to call the "add" function for each item.
extern crate iprange;
extern crate ipnet;
use std::net::Ipv4Addr;
use iprange::IpRange;
use ipnet::Ipv4Net;
use once_cell::sync::Lazy;
fn lookup(ip: String) -> bool {
IP_RANGES.contains(&ip.parse::<Ipv4Addr>().unwrap())
}
static IP_RANGES: Lazy<IpRange<Ipv4Net>> = Lazy::new(|| {
ranges()
.iter()
.map(|s| s.parse().unwrap())
.collect()
});
fn ranges() -> Vec<&'static str> {
vec![
"1.2.3.4/12",
]
}
Slight alternative which still has the error for calling the functions.
const IP_RANGES: IpRange<Ipv4Net> = {
let mut ip_ranges: IpRange<Ipv4Net> = IpRange::new();
ip_ranges.add("1.2.3.4/12".parse::<Ipv4Net>().unwrap());
ip_ranges
}
I get these errors.
cannot call non-const fn `IpRange::<Ipv4Net>::new` in constants
calls in constants are limited to constant functions, tuple structs and tuple variants
cannot call non-const fn `IpRange::<Ipv4Net>::add` in constants
calls in constants are limited to constant functions, tuple structs and tuple variants
Is there a way to move this struct create to compile time as it is fixed? I have looked at libraries like konst but this seems to be more for iterators and not functions in general. I have read there are open issues about allowing more logic in constant functions, but these have been open for a few years and there is a lot of debate.
Any ideas on how I can achieve a compile time data structure to avoid parsing or creating this at runtime are appreciated.