function cidrIntersect
cidrIntersect<T extends Cidr>(
a: T,
b: T extends Cidrv4 ? Cidrv4 : Cidrv6
): (T extends Cidrv4 ? Cidrv4 : Cidrv6) | null

Returns the intersection of two CIDR blocks.

Dispatches to cidrv4Intersect or cidrv6Intersect based on the address type. Throws TypeError when mixing IPv4 and IPv6 CIDRs. The result matches the dialect of the inputs, and is masked when they disagree (ADR 0006).

Examples

IPv4 intersection

import { assertEquals } from "@std/assert";
import { cidrIntersect, parseCidr, stringifyCidr } from "@hertzg/ip/cidr";

const result = cidrIntersect(parseCidr("10.0.0.0/8"), parseCidr("10.1.0.0/16"));
assertEquals(result && stringifyCidr(result), "10.1.0.0/16");

IPv6 intersection

import { assertEquals } from "@std/assert";
import { cidrIntersect, parseCidr, stringifyCidr } from "@hertzg/ip/cidr";

const result = cidrIntersect(parseCidr("2001:db8::/32"), parseCidr("2001:db8:1::/48"));
assertEquals(result && stringifyCidr(result), "2001:db8:1::/48");

Mixed versions throw TypeError

import { assertThrows } from "@std/assert";
import { cidrIntersect, parseCidr } from "@hertzg/ip/cidr";

assertThrows(
  () => cidrIntersect(parseCidr("10.0.0.0/8"), parseCidr("2001:db8::/32")),
  TypeError,
);

Type Parameters

T extends Cidr

Parameters

a: T

The first CIDR block

b: T extends Cidrv4 ? Cidrv4 : Cidrv6

The second CIDR block

Return Type

(T extends Cidrv4 ? Cidrv4 : Cidrv6) | null

The overlapping CIDR with canonical network address, or null if disjoint

Throws

TypeError

If the two CIDRs are different IP versions