function parseCidrv6
parseCidrv6(cidr: string): ParsedCidrv6

Parses IPv6 CIDR notation, in either dialect and with an optional zone ID, to a ParsedCidrv6.

The notation is address [ "%" zoneId ] "/" prefix (ADR 0003). The address is parsed as parseAddressv6 does, zone included. The prefix is a prefix length when it is decimal digits (no leading zero, no sign, no whitespace, no trailing text; 0 to 128), and a network mask when it contains a :, parsed with the same rules as an address. A mask is stored as given and is not required to be contiguous (ADR 0006): fe80::/ffff::ffff parses, and only cidrv6PrefixLength rejects it, because that is the call with no answer. An IPv4 mask on an IPv6 address (fe80::/255.0.0.0) is rejected.

An IPv4-mapped block stays IPv6 here; parseCidr is the parser that unmaps it.

Examples

Basic CIDR parsing

import { assertEquals } from "@std/assert";
import { parseCidrv6 } from "@hertzg/ip/cidrv6";

assertEquals(parseCidrv6("2001:db8::/32"), {
  address: 42540766411282592856903984951653826560n,
  prefixLength: 32,
});

The mask dialect is stored as a mask

import { assertEquals } from "@std/assert";
import { parseCidrv6 } from "@hertzg/ip/cidrv6";

assertEquals(parseCidrv6("fe80::/ffff:ffff::"), {
  address: 0xfe80n << 112n,
  mask: 0xFFFFFFFF000000000000000000000000n,
});

A zone ID is carried verbatim

import { assertEquals } from "@std/assert";
import { parseCidrv6 } from "@hertzg/ip/cidrv6";

assertEquals(parseCidrv6("fe80::%ether1/64"), {
  address: 0xfe80n << 112n,
  prefixLength: 64,
  zoneId: "ether1",
});

Error handling

import { assertThrows } from "@std/assert";
import { parseCidrv6 } from "@hertzg/ip/cidrv6";

assertThrows(() => parseCidrv6("2001:db8::"), TypeError);
assertThrows(() => parseCidrv6("2001:db8::/"), TypeError);
assertThrows(() => parseCidrv6("2001:db8::/129"), RangeError);
assertThrows(() => parseCidrv6("2001:db8::/032"), TypeError);
assertThrows(() => parseCidrv6("fe80::/255.0.0.0"), TypeError);
assertThrows(() => parseCidrv6("fe80::/64%eth0"), TypeError);
assertThrows(() => parseCidrv6("fe80::%/64"), TypeError);
assertThrows(() => parseCidrv6("192.168.1.0/24"), TypeError);

Parameters

cidr: string

The CIDR notation string, e.g. "2001:db8::/32", "fe80::/ffff:ffff::", "fe80::%ether1/64"

Return Type

The address and prefix length or mask as written, and the zone ID if there was one

Throws

TypeError

If the format is invalid: no prefix, a malformed address, prefix length or mask, a mask of the other version, an empty or malformed zone ID

RangeError

If a prefix length is a well-formed number outside 0 to 128, or an embedded IPv4 octet is greater than 255