Repository: achanda/ipnetwork (language: rust)

Issue:
const fn constructors
We can now/soon have `const fn` constructors thanks to `if` statements now working in `const` on nightly: https://blog.rust-lang.org/inside-rust/2019/11/25/const-if-match.html

We could implement it now already with a `nightly` feature and duplicate all constructors and conditionally compile them with `#[cfg(feature = "nightly")]`. But unless there is significant demand we could just wait and hope it reaches stable in a few versions.

This would improve the usability of this crate a lot. One of the most common ways I define IP networks in my code is global constants, which I currently have to use `lazy_static!` or similar to achieve.


Discussion / hints:
Adding the link to the tracking issue for if in `const fn`s here. For reference.
https://github.com/rust-lang/rust/issues/49146

Fix patch:
diff --git a/src/ipv4.rs b/src/ipv4.rs
index 9b0395a..a944598 100644
--- a/src/ipv4.rs
+++ b/src/ipv4.rs
@@ -35,7 +35,7 @@ impl Ipv4Network {
     /// Constructs a new `Ipv4Network` from any `Ipv4Addr` and a prefix denoting the network size.
     ///
     /// If the prefix is larger than 32 this will return an `IpNetworkError::InvalidPrefix`.
-    pub fn new(addr: Ipv4Addr, prefix: u8) -> Result<Ipv4Network, IpNetworkError> {
+    pub const fn new(addr: Ipv4Addr, prefix: u8) -> Result<Ipv4Network, IpNetworkError> {
         if prefix > IPV4_BITS {
             Err(IpNetworkError::InvalidPrefix)
         } else {
diff --git a/src/ipv6.rs b/src/ipv6.rs
index 4013086..558bc6e 100644
--- a/src/ipv6.rs
+++ b/src/ipv6.rs
@@ -36,7 +36,7 @@ impl Ipv6Network {
     /// Constructs a new `Ipv6Network` from any `Ipv6Addr` and a prefix denoting the network size.
     ///
     /// If the prefix is larger than 128 this will return an `IpNetworkError::InvalidPrefix`.
-    pub fn new(addr: Ipv6Addr, prefix: u8) -> Result<Ipv6Network, IpNetworkError> {
+    pub const fn new(addr: Ipv6Addr, prefix: u8) -> Result<Ipv6Network, IpNetworkError> {
         if prefix > IPV6_BITS {
             Err(IpNetworkError::InvalidPrefix)
         } else {


Test patch: