Skip to content

Commit 2716870

Browse files
Add ip_mask_to_prefix_checked
Make `ip_mask_to_prefix` const at the same time.
1 parent 4f433f9 commit 2716870

1 file changed

Lines changed: 12 additions & 1 deletion

File tree

src/lib.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,13 +426,24 @@ impl IntoIterator for &'_ IpNetwork {
426426

427427
/// Converts a `IpAddr` network mask into a prefix.
428428
/// If the mask is invalid this will return an `IpNetworkError::InvalidPrefix`.
429-
pub fn ip_mask_to_prefix(mask: IpAddr) -> Result<u8, IpNetworkError> {
429+
pub const fn ip_mask_to_prefix(mask: IpAddr) -> Result<u8, IpNetworkError> {
430430
match mask {
431431
IpAddr::V4(mask) => ipv4_mask_to_prefix(mask),
432432
IpAddr::V6(mask) => ipv6_mask_to_prefix(mask),
433433
}
434434
}
435435

436+
/// Converts a `IpAddr` network mask into a prefix.
437+
///
438+
/// If the mask is invalid this will return `None`. This is useful in const contexts where
439+
/// [`Option::unwrap`] may be called to trigger a compile-time error if the prefix is invalid.
440+
pub const fn ip_mask_to_prefix_checked(mask: IpAddr) -> Option<u8> {
441+
match mask {
442+
IpAddr::V4(mask) => ipv4_mask_to_prefix_checked(mask),
443+
IpAddr::V6(mask) => ipv6_mask_to_prefix_checked(mask),
444+
}
445+
}
446+
436447
#[cfg(test)]
437448
mod test {
438449
#[test]

0 commit comments

Comments
 (0)