Skip to content

Commit

Permalink
Merge pull request #36 from mcginty/ipnet-new
Browse files Browse the repository at this point in the history
add convenience `IpNet::new` method
  • Loading branch information
krisprice authored Feb 14, 2022
2 parents 9d54ef1 + d6e167b commit 88699c1
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 88699c1

Please sign in to comment.