function compareCidr
compareCidr(
a: Cidr,
b: Cidr
): -1 | 0 | 1

Compares two CIDR blocks of either version for sorting.

The order is version-first and total: every Cidrv4 sorts before every Cidrv6, and within a version blocks sort by address ascending, then by prefix length ascending — the shorter prefix (the larger block) first. Mixed-version arguments are not an error: unlike the other universal CIDR operations in this module, this function never throws, because sorting a mixed list is the reason it exists. Ordering a disjoint union needs no cross-version conversion — see ADR 0005.

The block is ordered as written: the address field is compared as stored, without applying the network mask first. See compareCidrv4 for what that means for blocks carrying host bits, and for why both dialects are compared by mask.

Examples

Sort a mixed dual-stack allowlist

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

const allowlist = [
  "2001:db8::/32",
  "192.168.1.0/24",
  "10.0.0.0/16",
  "fd00::/8",
  "10.0.0.0/8",
].map((s) => parseCidr(s));

assertEquals(allowlist.toSorted(compareCidr).map(stringifyCidr), [
  "10.0.0.0/8",
  "10.0.0.0/16",
  "192.168.1.0/24",
  "2001:db8::/32",
  "fd00::/8",
]);

Mixed versions sort, they do not throw

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

assertEquals(compareCidr(parseCidr("255.0.0.0/8"), parseCidr("::/0")), -1);
assertEquals(compareCidr(parseCidr("::/0"), parseCidr("0.0.0.0/0")), 1);

Parameters

The first CIDR block

The second CIDR block

Return Type

-1 | 0 | 1

-1 if a sorts before b, 1 if after, 0 if equal