Add const unsafe new_unchecked to Ipv4Network & Ipv6Network (#185)

* Add const unsafe `new_unchecked` to `Ipv4Network` & `Ipv6Network`

* New tests added for `new_unchecked` functions
This commit is contained in:
Aurélie Alvet
2023-12-21 16:03:04 +01:00
committed by GitHub
parent 817b5babed
commit a1966d4089
3 changed files with 29 additions and 1 deletions

View File

@ -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. /// Constructs a new `Ipv4Network` from a network address and a network mask.
/// ///
/// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`. /// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`.
@ -362,6 +368,14 @@ mod test {
assert!(net.is_err()); 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] #[test]
fn parse_v4_24bit() { fn parse_v4_24bit() {
let cidr: Ipv4Network = "127.1.0.0/24".parse().unwrap(); let cidr: Ipv4Network = "127.1.0.0/24".parse().unwrap();

View File

@ -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. /// Constructs a new `Ipv6Network` from a network address and a network mask.
/// ///
/// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`. /// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`.
@ -410,6 +416,15 @@ mod test {
assert!(cidr.is_err()); 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] #[test]
fn parse_v6() { fn parse_v6() {
let cidr: Ipv6Network = "::1/0".parse().unwrap(); let cidr: Ipv6Network = "::1/0".parse().unwrap();

View File

@ -3,7 +3,6 @@
#![crate_type = "lib"] #![crate_type = "lib"]
#![deny( #![deny(
missing_debug_implementations, missing_debug_implementations,
unsafe_code,
unused_extern_crates, unused_extern_crates,
unused_import_braces unused_import_braces
)] )]