Skip to content

Commit

Permalink
add convenience IpNet::new method
Browse files Browse the repository at this point in the history
  • Loading branch information
mcginty committed Jan 31, 2022
1 parent 7fd6856 commit d6e167b
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/ipnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,28 @@ impl fmt::Display for PrefixLenError {
impl Error for PrefixLenError {}

impl IpNet {
/// Creates a new IP network address from an `IpAddr` and prefix
/// length.
///
/// # Examples
///
/// ```
/// use std::net::Ipv6Addr;
/// use ipnet::{IpNet, PrefixLenError};
///
/// let net = IpNet::new(Ipv6Addr::LOCALHOST.into(), 48);
/// assert!(net.is_ok());
///
/// let bad_prefix_len = IpNet::new(Ipv6Addr::LOCALHOST.into(), 129);
/// assert_eq!(bad_prefix_len, Err(PrefixLenError));
/// ```
pub fn new(ip: IpAddr, prefix_len: u8) -> Result<IpNet, PrefixLenError> {
Ok(match ip {
IpAddr::V4(a) => Ipv4Net::new(a, prefix_len)?.into(),
IpAddr::V6(a) => Ipv6Net::new(a, prefix_len)?.into(),
})
}

/// Returns a copy of the network with the address truncated to the
/// prefix length.
///
Expand Down

0 comments on commit d6e167b

Please sign in to comment.