Skip to content

Commit

Permalink
Add largest identical prefix of two IP addresses function
Browse files Browse the repository at this point in the history
  • Loading branch information
rikonaka committed Oct 31, 2023
1 parent b15b85d commit eec6b4f
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "subnetwork"
version = "0.3.7"
version = "0.3.8"
edition = "2021"
license = "MIT"
description = "Return all ip addresses of a subnetwork"
Expand Down
73 changes: 73 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,35 @@ impl Ipv4 {
message: subnet_address.to_string(),
})
}
/// Returns the largest identical prefix of two IP addresses.
/// # Example
/// ```
/// use subnetwork::{Ipv4, Ipv4Pool};
///
/// fn main() {
/// let ipv4_1 = Ipv4::from("192.168.1.136").unwrap();
/// let ipv4_2 = Ipv4::from("192.168.1.192").unwrap();
/// let ret = ipv4_1.largest_identical_prefix(ipv4_2);
/// assert_eq!(ret, 25);
/// }
/// ```
pub fn largest_identical_prefix(&self, target: Ipv4) -> u32 {
let a = self.addr;
let b = target.addr;
let mut mask = 1;
for _ in 0..31 {
mask <<= 1;
}
let mut count = 0;
for _ in 0..32 {
if a & mask != b & mask {
break;
}
count += 1;
mask >>= 1;
}
count
}
}

impl Ipv6 {
Expand Down Expand Up @@ -717,6 +746,23 @@ impl Ipv6 {
message: subnet_address.to_string(),
})
}
pub fn max_identical_prefix(&self, target: Ipv6) -> u128 {
let a = self.addr;
let b = target.addr;
let mut mask = 1;
for _ in 0..127 {
mask <<= 1;
}
let mut count = 0;
for _ in 0..128 {
if a & mask != b & mask {
break;
}
count += 1;
mask >>= 1;
}
count - 1
}
}

#[cfg(test)]
Expand Down Expand Up @@ -905,4 +951,31 @@ mod tests {
println!("{:?}", size);
assert_eq!(size, 254);
}
#[test]
fn test_largest_identical_prefix() {
let ipv4_1 = Ipv4::from("192.168.1.136").unwrap();
let ipv4_2 = Ipv4::from("192.168.1.192").unwrap();
let ret = ipv4_1.largest_identical_prefix(ipv4_2);
println!("{}", ret);
}
#[test]
fn test_max_idt() {
let a: u32 = 14;
let b: u32 = 12;
let mut mask = 1;
for _ in 0..31 {
mask <<= 1;
}
println!("{}", mask);

let mut count = 0;
for _ in 0..32 {
if a & mask != b & mask {
break;
}
count += 1;
mask >>= 1;
}
println!("{}", count);
}
}

0 comments on commit eec6b4f

Please sign in to comment.