Skip to content

Commit 6812b4c

Browse files
committed
Add subnet_mask and tests
This was actually 95% done months ago, but I'm just committing it now.
1 parent 0362ee6 commit 6812b4c

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

‎src/lib.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,18 @@ impl MaskedIpAddr {
266266
self.cidr()
267267
}
268268

269+
/// Returns the subnet mask, calculated from the CIDR.
270+
pub fn subnet_mask(&self) -> u128 {
271+
fn cidr2mask(full_cidr: u8, cidr: u8, max: u128) -> u128 {
272+
(!((1 << full_cidr - cidr) - 1)) & max
273+
}
274+
275+
match self.addr {
276+
IpAddr::V4(_) => cidr2mask(IPV4_CIDR_FULL, self.cidr, std::u32::MAX as u128),
277+
IpAddr::V6(_) => cidr2mask(IPV6_CIDR_FULL, self.cidr, std::u128::MAX),
278+
}
279+
}
280+
269281
/// Consumes the `MaskedIpAddr`, returning the IP address and netmask.
270282
///
271283
/// # Examples

‎src/tests.rs‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ fn _db() -> Connection {
2424
conn.execute(
2525
"CREATE TEMPORARY TABLE foo (id SERIAL PRIMARY KEY, cidr CIDR, inet INET)",
2626
&[],
27-
).unwrap();
27+
)
28+
.unwrap();
2829
conn
2930
}
3031

@@ -51,7 +52,7 @@ fn _new_masked_ipv4() -> (MaskedIpAddr, IpAddr, u8) {
5152

5253
fn _new_masked_ipv6() -> (MaskedIpAddr, IpAddr, u8) {
5354
let expected = IpAddr::V6(Ipv6Addr::new(0x2001, 0xDB8, 0, 0, 0, 0, 0, 0));
54-
let cidr = 32;
55+
let cidr = 48;
5556

5657
(MaskedIpAddr::new(expected, cidr), expected, cidr)
5758
}
@@ -242,6 +243,18 @@ fn netmask_ipv6() {
242243
assert_eq!(mip.netmask(), cidr);
243244
}
244245

246+
#[test]
247+
fn subnet_mask_v4() {
248+
let (mip, _, _) = _new_masked_ipv4();
249+
assert_eq!(mip.subnet_mask(), 0xffffff00);
250+
}
251+
252+
#[test]
253+
fn subnet_mask_v6() {
254+
let (mip, _, _) = _new_masked_ipv6();
255+
assert_eq!(mip.subnet_mask(), 0xffffffffffff00000000000000000000);
256+
}
257+
245258
#[test]
246259
fn into_inner_ipv4() {
247260
let (mip, expected, cidr) = _new_full_ipv4();

0 commit comments

Comments
 (0)