Skip to content

Commit

Permalink
Add const unsafe new_unchecked to Ipv4Network & Ipv6Network (#185)
Browse files Browse the repository at this point in the history
* Add const unsafe `new_unchecked` to `Ipv4Network` & `Ipv6Network`

* New tests added for `new_unchecked` functions
  • Loading branch information
aurelilys committed Dec 21, 2023
1 parent 817b5ba commit a1966d4
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
14 changes: 14 additions & 0 deletions src/ipv4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ impl Ipv4Network {
}
}

/// Constructs without checking prefix a new `Ipv4Network` from any `Ipv4Addr,
/// and a prefix denoting the network size.
pub const unsafe fn new_unchecked(addr: Ipv4Addr, prefix: u8) -> Ipv4Network {
Ipv4Network { addr, prefix }
}

/// Constructs a new `Ipv4Network` from a network address and a network mask.
///
/// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`.
Expand Down Expand Up @@ -362,6 +368,14 @@ mod test {
assert!(net.is_err());
}

#[test]
fn create_unchecked_v4() {
let cidr = unsafe { Ipv4Network::new_unchecked(Ipv4Addr::new(77, 88, 21, 11), 24) };
assert_eq!(cidr.prefix(), 24);
let cidr = unsafe { Ipv4Network::new_unchecked(Ipv4Addr::new(0, 0, 0, 0), 33) };
assert_eq!(cidr.prefix(), 33);
}

#[test]
fn parse_v4_24bit() {
let cidr: Ipv4Network = "127.1.0.0/24".parse().unwrap();
Expand Down
15 changes: 15 additions & 0 deletions src/ipv6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,12 @@ impl Ipv6Network {
}
}

/// Constructs without checking prefix a new `Ipv6Network` from any `Ipv6Addr,
/// and a prefix denoting the network size.
pub const unsafe fn new_unchecked(addr: Ipv6Addr, prefix: u8) -> Ipv6Network {
Ipv6Network { addr, prefix }
}

/// Constructs a new `Ipv6Network` from a network address and a network mask.
///
/// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`.
Expand Down Expand Up @@ -410,6 +416,15 @@ mod test {
assert!(cidr.is_err());
}

#[test]
fn create_unchecked_v6() {
let cidr = unsafe { Ipv6Network::new_unchecked(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 24) };
assert_eq!(cidr.prefix(), 24);
let cidr =
unsafe { Ipv6Network::new_unchecked(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 129) };
assert_eq!(cidr.prefix(), 129);
}

#[test]
fn parse_v6() {
let cidr: Ipv6Network = "::1/0".parse().unwrap();
Expand Down
1 change: 0 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
#![crate_type = "lib"]
#![deny(
missing_debug_implementations,
unsafe_code,
unused_extern_crates,
unused_import_braces
)]
Expand Down

0 comments on commit a1966d4

Please sign in to comment.