krisprice / ipnet

IpNet, Ipv4Net, and Ipv6Net types and methods for Rust
Apache License 2.0
122 stars 26 forks source link

Allow to invoke some functions as const fn #43

Closed tetsuharuohzeki closed 1 year ago

tetsuharuohzeki commented 2 years ago

This change enables to invoke functions marked as const in this change in const context.

By this change, for example, we can construct Ipv6Net or Ipv4Net as a global constant during a compile time. This is useful when we crate a giant table.

thomastoye commented 1 year ago

Thank you @tetsuharuohzeki, I was about to create a similar PR myself.

@krisprice Would you consider merging this? I was able to merge master into this branch without any conflicts and the tests are passing.

This would be useful for declaring constants. Currently, I have

#[derive(Debug, Clone, Copy)]
pub struct Configuration {
    pub something: ...,
    pub bind_address: Ipv4Addr,
    pub remote_network: Ipv4Net,
}

I cannot create a constant holding example configuration:

pub const SIMULATOR_CONFIG: Configuration = Configuration {
  something: 123, // this works
  bind_address: Ipv4Addr::new(192, 168, 10, 1), // this works, Ipv4Addr::new is const
  remote_network: Ipv4Net::new( // This does not work, Ipv4Net::new is not const
    Ipv4Addr::new(10, 0, 0, 0),
    8
  )
}

Instead, I have to create a function to return a simple configuration like this. Having Ipv4Net::new as const would make this easier and cleaner.

krisprice commented 1 year ago

Sorry I meant to include it in the last release. Merged and new crate published. Thanks guys.

tetsuharuohzeki commented 1 year ago

@krisprice thank you!