// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! An IPv6 network in CIDR notation (RFC 4632), as in `2001:db8::/32`. //! //! The stored address is always the network address: every bit outside the //! prefix is zero. `parse` rejects text whose host bits are set, and //! `parseTruncate` clears them instead. const std = @import("std"); const json = @import("json.zig"); const Writer = std.Io.Writer; const decimal = @import("decimal.zig"); const Ipv6Address = @import("Ipv6Address.zig"); const Ipv6Network = @This(); /// The network address: the low `128 - prefix_len` bits are zero. address: Ipv6Address, /// Length of the routing prefix in bits, at most 128. prefix_len: u8, /// The default route, `::/0`, which contains every IPv6 address. pub const default_route: Ipv6Network = .{ .address = .unspecified, .prefix_len = 0 }; pub const InitError = error{ /// The prefix length was greater than 128. InvalidPrefixLength, /// Bits outside the prefix were set, as in `2001:db8::1/32`. HasHostBits, }; /// Builds a network, requiring the host bits of `address` to be clear. pub fn init(address: Ipv6Address, prefix_len: u8) InitError!Ipv6Network { if (prefix_len > Ipv6Address.bit_count) return error.InvalidPrefixLength; if (address.toInt() & ~netmaskInt(prefix_len) != 0) return error.HasHostBits; return .{ .address = address, .prefix_len = prefix_len }; } /// Builds a network from any address in it, clearing the host bits. pub fn initTruncate(address: Ipv6Address, prefix_len: u8) error{InvalidPrefixLength}!Ipv6Network { if (prefix_len > Ipv6Address.bit_count) return error.InvalidPrefixLength; return .{ .address = .fromInt(address.toInt() & netmaskInt(prefix_len)), .prefix_len = prefix_len, }; } /// The `/128` network holding exactly `address`. pub fn fromHost(address: Ipv6Address) Ipv6Network { return .{ .address = address, .prefix_len = Ipv6Address.bit_count }; } /// What can go wrong reading the text after `/`. `parsePrefixLen` returns /// these, and both parsers here include them. pub const PrefixError = error{ /// The text after `/` was not a decimal prefix length in the range 0 to /// 128. InvalidPrefix, /// The prefix length after `/` was greater than 128. InvalidPrefixLength, }; pub const ParseError = Ipv6Address.ParseError || InitError || PrefixError; /// Options accepted by `parseWithOptions`. Unlike the IPv4 form there is no /// netmask spelling to allow or refuse, so the only question is what to do /// with the host bits. pub const ParseOptions = struct { /// Clear the bits outside the prefix rather than rejecting them with /// `error.HasHostBits`, so that `2001:db8::1/32` yields `2001:db8::/32`. /// This is what `parseTruncate` sets. truncate_host_bits: bool = false, /// What an SPF record may write after `ip6:`, as RFC 7208 §5.6 defines it. /// /// `ip6-network` is the RFC 4291 §2.2 text form, which is what /// `Ipv6Address.parse` already accepts and no more -- no zone identifier, /// no brackets -- and `ip6-cidr-length = "/" ("0" / %x31-39 0*2DIGIT)`, /// a value of 0 to 128, is what `parsePrefixLen` already accepts and no /// more. So the whole of the difference is the host bits: the mechanism /// compares only the high-order bits of the address, which makes /// `ip6:2001:db8::1/32` a legal way to write `2001:db8::/32` rather than /// the error the default would make of it. /// /// Only the network is parsed, so strip the `ip6:` first. pub const spf: ParseOptions = .{ .truncate_host_bits = true }; }; /// Parses CIDR notation, as in `2001:db8::/32`. /// /// Text with no `/` at all is read as a single host, equivalent to a `/128`. /// /// Host bits must be clear; `2001:db8::1/32` is rejected with /// `error.HasHostBits`. Use `parseTruncate` to accept and clear them, or /// `parseWithOptions` to say what a particular text form allows. pub fn parse(text: []const u8) ParseError!Ipv6Network { return parseWithOptions(text, .{}); } /// Like `parse`, but clears any host bits instead of rejecting them, so that /// `2001:db8::1/32` yields `2001:db8::/32`. pub fn parseTruncate(text: []const u8) ParseError!Ipv6Network { return parseWithOptions(text, .{ .truncate_host_bits = true }); } /// Like `parse`, but reading the text form that `options` describes. Use this /// for the stricter notation another standard defines, such as the `ip6:` of /// an SPF record: /// /// ``` /// const network = try Ipv6Network.parseWithOptions(term["ip6:".len..], .spf); /// ``` pub fn parseWithOptions(text: []const u8, options: ParseOptions) ParseError!Ipv6Network { const parsed = try parseParts(text); if (options.truncate_host_bits) return initTruncate(parsed.address, parsed.prefix_len); return init(parsed.address, parsed.prefix_len); } fn parseParts(text: []const u8) ParseError!struct { address: Ipv6Address, prefix_len: u8 } { const slash = std.mem.findScalar(u8, text, '/') orelse return .{ .address = try Ipv6Address.parse(text), .prefix_len = Ipv6Address.bit_count, }; return .{ .address = try Ipv6Address.parse(text[0..slash]), .prefix_len = try parsePrefixLen(text[slash + 1 ..]), }; } /// Parses the text that follows a `/`, which for IPv6 is always a decimal /// prefix length. Leading zeros are rejected, as they are everywhere else. /// /// `Ipv6Interface` reads its prefix through this, so the two types are strict /// about the same things. pub fn parsePrefixLen(text: []const u8) PrefixError!u8 { if (text.len == 0 or text.len > 3) return error.InvalidPrefix; if (text.len > 1 and text[0] == '0') return error.InvalidPrefix; var value: u16 = 0; for (text) |c| { const digit = c -% '0'; if (digit > 9) return error.InvalidPrefix; value = value * 10 + digit; } if (value > Ipv6Address.bit_count) return error.InvalidPrefixLength; return @intCast(value); } /// Whether `text` is valid CIDR notation with its host bits clear, discarding /// the reason when it is not. pub fn isValid(text: []const u8) bool { _ = parse(text) catch return false; return true; } fn netmaskInt(prefix_len: u8) u128 { if (prefix_len == 0) return 0; return ~@as(u128, 0) << @intCast(Ipv6Address.bit_count - prefix_len); } /// The netmask, as in `ffff:ffff::` for a `/32`. pub fn netmask(n: Ipv6Network) Ipv6Address { return .fromInt(netmaskInt(n.prefix_len)); } /// The complement of the netmask, as in `::ffff:ffff:ffff:ffff:ffff:ffff` for /// a `/32`. pub fn hostmask(n: Ipv6Network) Ipv6Address { return .fromInt(~netmaskInt(n.prefix_len)); } /// The first address in the network, which is its network address. IPv6 has no /// broadcast address, but this address is reserved as the subnet-router /// anycast address of a link (RFC 4291). pub fn networkAddress(n: Ipv6Network) Ipv6Address { return n.address; } /// The last address in the network. pub fn lastAddress(n: Ipv6Network) Ipv6Address { return .fromInt(n.address.toInt() | ~netmaskInt(n.prefix_len)); } /// Whether the network holds exactly one address, which is to say that its /// prefix length is the full width of the family: a `/32` for IPv4 or a /// `/128` for IPv6. /// /// This is worth asking as a question of its own because such a network is /// where a great deal of code has a special case — a route that is a host /// route, a firewall rule that names one machine, an access list entry /// written with no `/` at all — and reading `n.prefixLen() == Ipv6Address.bit_count` /// at each of those places says less about the intent than this does. pub fn isSingleAddress(n: Ipv6Network) bool { return n.prefix_len == Ipv6Address.bit_count; } /// The number of addresses in the network, from 1 for a `/128` up to 2^128 for /// a `/0`. The result is 129 bits wide because a `/0` does not fit in 128. pub fn addressCount(n: Ipv6Network) u129 { return @as(u129, 1) << @intCast(Ipv6Address.bit_count - n.prefix_len); } /// The number of usable host addresses. /// /// IPv6 has no broadcast address, so only one address is held back: the /// all-zeros interface identifier, which is the Subnet-Router anycast address /// of RFC 4291 §2.6.1 and belongs to every router on the link rather than to /// a host. The last address of the network is an ordinary host address, which /// is where this differs from `Ipv4Network.hostCount`. /// /// The two exceptions mirror IPv4's. A `/127` is an inter-router link whose /// two addresses are both usable (RFC 6164) — the anycast address is not /// reserved there, because with only two addresses reserving one would leave /// a link with a single usable address. A `/128` is a single host. pub fn hostCount(n: Ipv6Network) u129 { return switch (n.prefix_len) { 128 => 1, 127 => 2, else => n.addressCount() - 1, }; } /// The first usable host address. pub fn firstHost(n: Ipv6Network) Ipv6Address { if (n.prefix_len >= 127) return n.address; return .fromInt(n.address.toInt() + 1); } /// The last usable host address, which for IPv6 is always the last address of /// the network. It is here so that code handling both versions can ask the /// same question of either; `Ipv4Network.lastHost` is the one that has to /// step back past a broadcast address. pub fn lastHost(n: Ipv6Network) Ipv6Address { return n.lastAddress(); } /// Whether `address` falls inside the network. pub fn contains(n: Ipv6Network, address: Ipv6Address) bool { return address.toInt() & netmaskInt(n.prefix_len) == n.address.toInt(); } /// Whether every address of `other` also falls inside `n`. pub fn containsNetwork(n: Ipv6Network, other: Ipv6Network) bool { return other.prefix_len >= n.prefix_len and n.contains(other.address); } /// Whether the two networks share any address. Two networks either nest or are /// disjoint, so this is true exactly when one contains the other. pub fn overlaps(n: Ipv6Network, other: Ipv6Network) bool { return n.contains(other.address) or other.contains(n.address); } /// The network one bit shorter than this one, or the network with the given /// prefix length when `new_prefix_len` is supplied. pub fn supernet(n: Ipv6Network, new_prefix_len: ?u8) error{InvalidPrefixLength}!Ipv6Network { const prefix_len = new_prefix_len orelse (if (n.prefix_len == 0) return error.InvalidPrefixLength else n.prefix_len - 1); if (prefix_len > n.prefix_len) return error.InvalidPrefixLength; return initTruncate(n.address, prefix_len); } /// The part of this network that is left once `other` is taken out of it, /// as a sequence of whole networks. /// /// Removing one prefix from another cannot leave one prefix behind — take a /// `/26` out of a `/24` and what is left is a `/25` and a `/26` — so the /// answer is an iterator. It yields at most `other.prefixLen() - /// prefixLen()` networks, which is 32 at the very worst for IPv4 and 128 for /// IPv6, and it allocates nothing: each block is computed from the path down /// to `other` as it goes. The blocks are disjoint, none of them overlaps /// `other`, and together they cover exactly the remainder. /// /// The three cases it has to handle, none of which is an error: /// /// * `other` lies outside this network, so nothing is removed and the one /// network yielded is this one. /// * `other` covers this network, so everything is removed and nothing is /// yielded. /// * `other` lies strictly inside, which is the interesting case above. /// /// The blocks come out largest first, which is the order they are found in /// walking down to `other`. That is not address order and cannot be: which /// side of `other` each block falls on depends on where in the network /// `other` sits. /// /// This is the operation a firewall or a routing table is built out of — /// "this range, except that part of it" — and the one thing CIDR notation /// cannot write down directly. pub fn exclude(n: Ipv6Network, other: Ipv6Network) ExcludeIterator { if (!n.overlaps(other)) return .initWhole(n); if (other.containsNetwork(n)) return .initEmpty(); return .{ .whole = null, .target = other.address, .next_len = n.prefix_len + 1, .last_len = other.prefix_len, }; } pub const ExcludeIterator = struct { /// Set only in the case where nothing was removed, and handed back by the /// first `next` call. whole: ?Ipv6Network, /// The network being removed. Only its leading bits are read: the block /// to yield at each level is the sibling of `target`'s prefix at that /// level, which is the half of it that `target` is not in. target: Ipv6Address, next_len: u8, last_len: u8, /// An iterator over `network` alone, which is what `exclude` returns when /// there was nothing in it to remove. pub fn initWhole(network: Ipv6Network) ExcludeIterator { return .{ .whole = network, .target = undefined, .next_len = 1, .last_len = 0 }; } /// An iterator over nothing, which is what `exclude` returns when the /// whole network was removed. pub fn initEmpty() ExcludeIterator { return .{ .whole = null, .target = undefined, .next_len = 1, .last_len = 0 }; } pub fn next(it: *ExcludeIterator) ?Ipv6Network { if (it.whole) |network| { it.whole = null; return network; } if (it.next_len > it.last_len) return null; const len = it.next_len; it.next_len += 1; // The bit that tells the two halves at this level apart. Flipping it // in `target`'s prefix names the half `target` is not in, which is // therefore entirely outside `other` and entirely inside `n`. const bit = @as(u128, 1) << @intCast(Ipv6Address.bit_count - len); const prefix = it.target.toInt() & netmaskInt(len); return .{ .address = .fromInt(prefix ^ bit), .prefix_len = len }; } test next { // Three levels down, so three blocks. var it = (try parse("2001:db8::/32")).exclude(try .parse("2001:db8::/35")); var count: usize = 0; while (it.next()) |_| count += 1; try std.testing.expectEqual(@as(usize, 3), count); } }; /// Splits the network into equal subnets of length `new_prefix_len`, which /// must be at least as long as this network's prefix. pub fn subnets(n: Ipv6Network, new_prefix_len: u8) error{InvalidPrefixLength}!SubnetIterator { if (new_prefix_len < n.prefix_len or new_prefix_len > Ipv6Address.bit_count) { return error.InvalidPrefixLength; } const start: u129 = n.address.toInt(); return .{ .next_value = start, .end_value = start + n.addressCount(), .step = @as(u129, 1) << @intCast(Ipv6Address.bit_count - new_prefix_len), .prefix_len = new_prefix_len, }; } pub const SubnetIterator = struct { next_value: u129, end_value: u129, step: u129, prefix_len: u8, pub fn next(it: *SubnetIterator) ?Ipv6Network { if (it.next_value >= it.end_value) return null; const value: u128 = @intCast(it.next_value); it.next_value += it.step; return .{ .address = .fromInt(value), .prefix_len = it.prefix_len }; } test next { var it = try (try parse("2001:db8::/32")).subnets(34); try std.testing.expect(it.next().?.eql(try parse("2001:db8::/34"))); try std.testing.expect(it.next().?.eql(try parse("2001:db8:4000::/34"))); try std.testing.expect(it.next().?.eql(try parse("2001:db8:8000::/34"))); try std.testing.expect(it.next().?.eql(try parse("2001:db8:c000::/34"))); // Null once the network is used up, so a `while` loop ends on its own. try std.testing.expectEqual(null, it.next()); } }; /// Iterates over every address in the network. An IPv6 network is usually far /// too large to enumerate; this is meant for the small prefixes where doing so /// makes sense. pub fn addresses(n: Ipv6Network) AddressIterator { const start: u129 = n.address.toInt(); return .{ .next_value = start, .end_value = start + n.addressCount() }; } /// Iterates over the usable host addresses, skipping the Subnet-Router /// anycast address of a `/126` or shorter prefix. /// /// A `/64` has 2^64 - 1 of them, so this is an iterator that will not finish /// in any useful time; it is for the small networks where enumerating is the /// point, and `hostCount` is the way to ask how many there are. pub fn hosts(n: Ipv6Network) AddressIterator { const first: u129 = n.firstHost().toInt(); return .{ .next_value = first, .end_value = first + n.hostCount() }; } pub const AddressIterator = struct { next_value: u129, end_value: u129, pub fn next(it: *AddressIterator) ?Ipv6Address { if (it.next_value >= it.end_value) return null; const value: u128 = @intCast(it.next_value); it.next_value += 1; return .fromInt(value); } test next { var it = (try parse("2001:db8::/126")).addresses(); try std.testing.expect(it.next().?.eql(try .parse("2001:db8::"))); try std.testing.expect(it.next().?.eql(try .parse("2001:db8::1"))); try std.testing.expect(it.next().?.eql(try .parse("2001:db8::2"))); try std.testing.expect(it.next().?.eql(try .parse("2001:db8::3"))); // Null once the network is used up, so a `while` loop ends on its own. try std.testing.expectEqual(null, it.next()); } }; /// Sorts `networks` in place and folds it down to the smallest set of /// networks covering exactly the same addresses, returning the prefix of the /// slice that survives. /// /// Two things are folded away: a network already inside another disappears, /// and two networks that are the two halves of one larger network become that /// larger network. The second is applied repeatedly, so four adjacent `/26`s /// come out as one `/24`, and it is why the result can be shorter than /// anything a single pass over the input would produce. /// /// This is the operation that keeps a generated access list or route set from /// growing without bound — the one thing on this type that is naturally a /// whole-collection operation rather than a question about one network. /// /// It takes a mutable slice rather than an allocator because sorting is the /// only thing it needs and sorting can be done in place. The caller owns the /// storage, decides where it came from, and keeps whatever is past the /// returned slice — those entries are still the caller's networks, merely no /// longer needed, rather than freed memory. /// /// ``` /// var list = [_]Ipv6Network{ a, b, c }; /// for (Ipv6Network.merge(&list)) |network| ... /// ``` pub fn merge(networks: []Ipv6Network) []Ipv6Network { // Unstable, because under this comparator two networks that compare // equal are the same network and there is no order between them to // preserve. std.mem.sortUnstable(Ipv6Network, networks, {}, lessThan); // The front of the slice doubles as a stack of the networks kept so far, // which is what makes this allocation-free: nothing survives that was not // already in the input, and it can only move towards the front. var kept: usize = 0; for (networks) |candidate| { var network = candidate; // Sorted order puts a containing network before everything inside it, // and the networks kept so far are disjoint, so only the top of the // stack can possibly contain or join this one. Combining can expose // another pair, so this repeats: `.0/26`, `.64/26`, `.128/25` folds // twice. while (kept > 0) { const top = networks[kept - 1]; if (top.containsNetwork(network)) break; network = join(top, network) orelse break; kept -= 1; } if (kept > 0 and networks[kept - 1].containsNetwork(network)) continue; networks[kept] = network; kept += 1; } return networks[0..kept]; } fn lessThan(_: void, a: Ipv6Network, b: Ipv6Network) bool { return a.order(b) == .lt; } /// The one network that covers both exactly, when they are the two halves of /// it, and null otherwise. Order does not matter. /// /// Being adjacent is not enough and neither is being the same size. A `/33` /// and the `/34` after it touch without being halves of anything, and so do /// the upper `/34` of one `/33` and the lower `/34` of the next: halves are /// two networks of the same size that differ in exactly the bit their length /// makes significant, which means the lower of them has that bit clear. /// /// This is the step `merge` is built out of, and it is worth having on its /// own wherever the question is whether two entries in a list can be written /// as one. pub fn join(a: Ipv6Network, b: Ipv6Network) ?Ipv6Network { if (a.prefix_len != b.prefix_len or a.prefix_len == 0) return null; const lower = if (a.address.toInt() <= b.address.toInt()) a else b; const upper = if (a.address.toInt() <= b.address.toInt()) b else a; const bit = @as(u128, 1) << @intCast(Ipv6Address.bit_count - a.prefix_len); const low = lower.address.toInt(); if (low & bit != 0) return null; if (low | bit != upper.address.toInt()) return null; return .{ .address = lower.address, .prefix_len = lower.prefix_len - 1 }; } pub fn eql(n: Ipv6Network, other: Ipv6Network) bool { return n.prefix_len == other.prefix_len and n.address.eql(other.address); } /// Orders by network address first, then by prefix length, so that a /// containing network sorts before the networks inside it. pub fn order(n: Ipv6Network, other: Ipv6Network) std.math.Order { return switch (n.address.order(other.address)) { .eq => std.math.order(n.prefix_len, other.prefix_len), else => |result| result, }; } /// The longest text an IPv6 network can format to. pub const max_text_len = Ipv6Address.max_text_len + "/128".len; /// Writes the network in CIDR notation. Use the `{f}` specifier. pub fn format(n: Ipv6Network, w: *Writer) Writer.Error!void { var buffer: [render_len]u8 = undefined; try w.writeAll(n.render(&buffer)); } /// Formats into `buffer`, returning the written slice. The buffer must be at /// least `max_text_len` bytes. pub fn bufPrint(n: Ipv6Network, buffer: []u8) error{NoSpaceLeft}![]u8 { var rendered: [render_len]u8 = undefined; const text = n.render(&rendered); if (buffer.len < text.len) return error.NoSpaceLeft; @memcpy(buffer[0..text.len], text); return buffer[0..text.len]; } /// Room for the longest text plus the spill of `decimal.renderSmall`. const render_len = Ipv6Address.max_text_len + "/".len + 4; /// Renders the CIDR notation into `buffer`, returning the written slice. This /// is the one place the text is produced; `format` and `bufPrint` both go /// through it rather than through `Writer.print`, whose per-integer formatting /// costs more than the whole network. fn render(n: Ipv6Network, buffer: *[render_len]u8) []u8 { const address = n.address.bufPrint(buffer[0..Ipv6Address.max_text_len]) catch unreachable; var len = address.len; buffer[len] = '/'; len += 1; len += decimal.renderSmall(n.prefix_len, buffer[len..][0..4]); return buffer[0..len]; } /// Writes the value as a JSON string. See `json.stringify`. pub fn jsonStringify(value: Ipv6Network, jws: anytype) !void { return json.stringify(value, jws); } /// Reads a JSON string with `parse`. See `json.parse` for what happens to the /// reason when the text is rejected. pub fn jsonParse( allocator: std.mem.Allocator, source: anytype, options: std.json.ParseOptions, ) !Ipv6Network { _ = options; return json.parse(Ipv6Network, allocator, source); } const testing = std.testing; test parse { const n = try parse("2001:db8::/32"); try testing.expectEqual(try Ipv6Address.parse("2001:db8::"), n.address); try testing.expectEqual(@as(u8, 32), n.prefix_len); try testing.expect((try parse("::/0")).eql(default_route)); try testing.expect((try parse("fe80::/10")).eql(try init(try .parse("fe80::"), 10))); // Text without a prefix is a single host. try testing.expect((try parse("::1")).eql(fromHost(.loopback))); try testing.expect((try parse("::1/128")).eql(fromHost(.loopback))); } test "parse rejects malformed text" { try testing.expectError(error.HasHostBits, parse("2001:db8::1/32")); try testing.expectError(error.HasHostBits, parse("fe80::1/10")); try testing.expectError(error.InvalidPrefixLength, parse("2001:db8::/129")); try testing.expectError(error.InvalidPrefix, parse("2001:db8::/")); try testing.expectError(error.InvalidPrefix, parse("2001:db8::/032")); try testing.expectError(error.InvalidPrefix, parse("2001:db8::/1000")); try testing.expectError(error.InvalidPrefix, parse("2001:db8::/x")); try testing.expectError(error.InvalidPrefix, parse("2001:db8::/32 ")); try testing.expectError(error.TooFewGroups, parse("2001:db8/32")); try testing.expectError(error.UnexpectedZone, parse("fe80::1%eth0/128")); } test parseTruncate { try testing.expect((try parseTruncate("2001:db8::1/32")).eql(try parse("2001:db8::/32"))); try testing.expect((try parseTruncate("2001:db8::1/0")).eql(default_route)); try testing.expect((try parseTruncate("::1/128")).eql(fromHost(.loopback))); } test "the SPF form of ip6-network" { try testing.expect((try parseWithOptions("2001:db8::/32", .spf)) .eql(try parse("2001:db8::/32"))); // Section 5.6's own example of an `ip6-network`, which carries no length // and so is a /128, as that section says in as many words. try testing.expect((try parseWithOptions("2001:db8::cd30", .spf)) .eql(fromHost(try .parse("2001:db8::cd30")))); try testing.expect((try parseWithOptions("::/0", .spf)).eql(default_route)); // The mechanism compares high-order bits, so host bits are something to // ignore rather than to refuse. try testing.expect((try parseWithOptions("2001:db8::1/32", .spf)) .eql(try parse("2001:db8::/32"))); // `ip6-network` is the RFC 4291 section 2.2 form and nothing else, and // `ip6-cidr-length` is one to three digits with no leading zero -- all of // which the default parser is already strict about, so the option has // nothing to add. try testing.expectError(error.InvalidPrefix, parseWithOptions("2001:db8::/032", .spf)); try testing.expectError(error.InvalidPrefixLength, parseWithOptions("2001:db8::/129", .spf)); try testing.expectError(error.UnexpectedZone, parseWithOptions("fe80::1%eth0/64", .spf)); try testing.expectError(error.InvalidCharacter, parseWithOptions("[2001:db8::]/32", .spf)); // The dotted-quad tail is part of that form, so it stays legal. try testing.expect((try parseWithOptions("::ffff:192.0.2.0/120", .spf)) .eql(try parse("::ffff:192.0.2.0/120"))); } test jsonStringify { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try std.json.Stringify.value(try Ipv6Network.parse("2001:db8::/32"), .{}, &w); // A JSON string holding exactly what `format` would have written. try testing.expectEqualStrings("\"2001:db8::/32\"", w.buffered()); } test jsonParse { // The hook is driven directly rather than through `parseFromSlice`, so // that this tests the function it is named after and nothing else; // `root.zig` has the end-to-end one. var scanner = std.json.Scanner.initCompleteInput(testing.allocator, "\"2001:db8::/32\""); defer scanner.deinit(); const value = try Ipv6Network.jsonParse(testing.allocator, &scanner, .{}); try testing.expect(value.eql(try Ipv6Network.parse("2001:db8::/32"))); // As strict inside a JSON document as anywhere else, though the reason is // flattened to `InvalidCharacter` on the way out. var bad = std.json.Scanner.initCompleteInput(testing.allocator, "\"2001:db8::1/32\""); defer bad.deinit(); try testing.expectError( error.InvalidCharacter, Ipv6Network.jsonParse(testing.allocator, &bad, .{}), ); // Anything that is not a string is the wrong shape rather than a bad // address. var number = std.json.Scanner.initCompleteInput(testing.allocator, "42"); defer number.deinit(); try testing.expectError( error.UnexpectedToken, Ipv6Network.jsonParse(testing.allocator, &number, .{}), ); } test format { try testing.expectFmt("2001:db8::/32", "{f}", .{try parse("2001:db8::/32")}); try testing.expectFmt("::/0", "{f}", .{default_route}); try testing.expectFmt("::1/128", "{f}", .{fromHost(.loopback)}); } test "masks and bounds" { const n = try parse("2001:db8::/32"); try testing.expectFmt("ffff:ffff::", "{f}", .{n.netmask()}); try testing.expectFmt("::ffff:ffff:ffff:ffff:ffff:ffff", "{f}", .{n.hostmask()}); try testing.expectFmt("2001:db8::", "{f}", .{n.networkAddress()}); try testing.expectFmt("2001:db8:ffff:ffff:ffff:ffff:ffff:ffff", "{f}", .{n.lastAddress()}); try testing.expectEqual(@as(u129, 1) << 96, n.addressCount()); // A /0 covers the whole address space without overflowing. try testing.expectEqual(@as(u129, 1) << 128, default_route.addressCount()); try testing.expectFmt("::", "{f}", .{default_route.netmask()}); try testing.expectFmt("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", "{f}", .{default_route.lastAddress()}); const host = fromHost(.loopback); try testing.expectEqual(@as(u129, 1), host.addressCount()); try testing.expectFmt("::1", "{f}", .{host.lastAddress()}); } test contains { const n = try parse("2001:db8::/32"); try testing.expect(n.contains(try .parse("2001:db8::"))); try testing.expect(n.contains(try .parse("2001:db8:ffff::1"))); try testing.expect(!n.contains(try .parse("2001:db9::1"))); try testing.expect(default_route.contains(.loopback)); try testing.expect(n.containsNetwork(try parse("2001:db8:1::/48"))); try testing.expect(n.containsNetwork(n)); try testing.expect(!n.containsNetwork(try parse("2001:db9::/48"))); try testing.expect(!(try parse("2001:db8:1::/48")).containsNetwork(n)); try testing.expect(n.overlaps(try parse("2001:db8:1::/48"))); try testing.expect((try parse("2001:db8:1::/48")).overlaps(n)); try testing.expect(!n.overlaps(try parse("2001:db9::/32"))); } test exclude { // A `/26` out of a `/24` leaves a `/25` and a `/26`, largest first. var it = (try parse("2001:db8::/32")).exclude(try .parse("2001:db8::/34")); try std.testing.expect(it.next().?.eql(try .parse("2001:db8:8000::/33"))); try std.testing.expect(it.next().?.eql(try .parse("2001:db8:4000::/34"))); try std.testing.expectEqual(null, it.next()); // Nothing to remove: the network comes back whole. var apart = (try parse("2001:db8::/32")).exclude(try .parse("2001:db9::/32")); try std.testing.expect(apart.next().?.eql(try parse("2001:db8::/32"))); try std.testing.expectEqual(null, apart.next()); // Everything removed, including the case where the two are equal. var all = (try parse("2001:db8::/32")).exclude(try .parse("2001:d00::/24")); try std.testing.expectEqual(null, all.next()); var same = (try parse("2001:db8::/32")).exclude(try .parse("2001:db8::/32")); try std.testing.expectEqual(null, same.next()); // Whatever is excluded, the blocks left behind cover the rest exactly: // none contains the removed address, and their sizes add up. var total: u129 = 0; var parts = (try parse("2001:db8::/32")).exclude(try .parse("2001:db8::/34")); while (parts.next()) |part| { try std.testing.expect(!part.overlaps(try .parse("2001:db8::/34"))); total += part.addressCount(); } try std.testing.expectEqual( (try parse("2001:db8::/32")).addressCount() - (try parse("2001:db8::/34")).addressCount(), total, ); } test subnets { var it = try (try parse("2001:db8::/32")).subnets(34); try testing.expectFmt("2001:db8::/34", "{f}", .{it.next().?}); try testing.expectFmt("2001:db8:4000::/34", "{f}", .{it.next().?}); try testing.expectFmt("2001:db8:8000::/34", "{f}", .{it.next().?}); try testing.expectFmt("2001:db8:c000::/34", "{f}", .{it.next().?}); try testing.expectEqual(null, it.next()); // The whole space splits into two halves without overflowing. var halves = try default_route.subnets(1); try testing.expectFmt("::/1", "{f}", .{halves.next().?}); try testing.expectFmt("8000::/1", "{f}", .{halves.next().?}); try testing.expectEqual(null, halves.next()); try testing.expectError(error.InvalidPrefixLength, (try parse("2001:db8::/32")).subnets(31)); try testing.expectError(error.InvalidPrefixLength, (try parse("2001:db8::/32")).subnets(129)); } test supernet { try testing.expect((try (try parse("2001:db8::/32")).supernet(null)).eql(try parse("2001:db8::/31"))); try testing.expect((try (try parse("2001:db8::/32")).supernet(16)).eql(try parse("2001::/16"))); try testing.expectError(error.InvalidPrefixLength, default_route.supernet(null)); try testing.expectError(error.InvalidPrefixLength, (try parse("2001:db8::/32")).supernet(33)); } test addresses { var it = (try parse("2001:db8::/126")).addresses(); try testing.expectFmt("2001:db8::", "{f}", .{it.next().?}); try testing.expectFmt("2001:db8::1", "{f}", .{it.next().?}); try testing.expectFmt("2001:db8::2", "{f}", .{it.next().?}); try testing.expectFmt("2001:db8::3", "{f}", .{it.next().?}); try testing.expectEqual(null, it.next()); // The last network in the address space stops rather than wrapping. var last = (try parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc/126")).addresses(); var count: usize = 0; while (last.next()) |_| count += 1; try testing.expectEqual(@as(usize, 4), count); } test "ordering" { try testing.expectEqual(.lt, (try parse("2001:db8::/32")).order(try parse("2001:db8::/48"))); try testing.expectEqual(.lt, (try parse("2001:db8::/32")).order(try parse("2001:db9::/32"))); try testing.expectEqual(.eq, (try parse("2001:db8::/32")).order(try parse("2001:db8::/32"))); } test init { const network = try Ipv6Network.init(try .parse("2001:db8::"), 32); try testing.expect(network.eql(try parse("2001:db8::/32"))); // The host bits have to be clear; `initTruncate` is the one that clears // them. try testing.expectError(error.HasHostBits, Ipv6Network.init(try .parse("2001:db8::1"), 32)); try testing.expectError(error.InvalidPrefixLength, Ipv6Network.init(.unspecified, 129)); } test initTruncate { const network = try Ipv6Network.initTruncate(try .parse("2001:db8::1"), 32); try testing.expect(network.eql(try parse("2001:db8::/32"))); } test fromHost { const network = Ipv6Network.fromHost(try .parse("2001:db8::1")); try testing.expectEqual(@as(u8, 128), network.prefix_len); try testing.expectEqual(@as(u129, 1), network.addressCount()); } test parseWithOptions { // The `ip6:` of an SPF record compares only the prefix, so host bits are // a legal way to write the network rather than an error. try testing.expect((try parseWithOptions("2001:db8::1/32", .spf)).eql(try parse("2001:db8::/32"))); try testing.expectError(error.HasHostBits, parseWithOptions("2001:db8::1/32", .{})); } test parsePrefixLen { try testing.expectEqual(@as(u8, 64), try parsePrefixLen("64")); try testing.expectEqual(@as(u8, 128), try parsePrefixLen("128")); // No netmask form for IPv6, and no leading zeros. try testing.expectError(error.InvalidPrefix, parsePrefixLen("064")); try testing.expectError(error.InvalidPrefixLength, parsePrefixLen("129")); } test isValid { try testing.expect(isValid("2001:db8::/32")); // A bare address is a `/128` and so is valid notation. try testing.expect(isValid("2001:db8::1")); // Host bits are not, which is what separates a network from an interface. try testing.expect(!isValid("2001:db8::1/32")); } test netmask { try testing.expect((try parse("2001:db8::/32")).netmask().eql(try .parse("ffff:ffff::"))); try testing.expect((try parse("::/0")).netmask().eql(.unspecified)); } test hostmask { try testing.expect((try parse("2001:db8::/32")) .hostmask().eql(try .parse("::ffff:ffff:ffff:ffff:ffff:ffff"))); try testing.expect((try parse("2001:db8::1/128")).hostmask().eql(.unspecified)); } test networkAddress { // IPv6 has no broadcast address, but this one is reserved as the // subnet-router anycast address of the link. try testing.expect((try parse("2001:db8::/32")).networkAddress().eql(try .parse("2001:db8::"))); } test lastAddress { try testing.expect((try parse("2001:db8::/32")) .lastAddress().eql(try .parse("2001:db8:ffff:ffff:ffff:ffff:ffff:ffff"))); } test isSingleAddress { try testing.expect((try parse("2001:db8::1/128")).isSingleAddress()); try testing.expect(!(try parse("2001:db8::/64")).isSingleAddress()); // Text with no `/` parses as a single host, so it is one too. try testing.expect((try parse("2001:db8::1")).isSingleAddress()); } test addressCount { try testing.expectEqual(@as(u129, 1) << 64, (try parse("2001:db8::/64")).addressCount()); try testing.expectEqual(@as(u129, 1), (try parse("2001:db8::1/128")).addressCount()); // A `/0` is the whole address space, which is why the count is 129 bits // wide. try testing.expectEqual(@as(u129, 1) << 128, (try parse("::/0")).addressCount()); } test hostCount { // One address held back, not two: there is no broadcast address to // reserve, only the Subnet-Router anycast address. try testing.expectEqual(@as(u129, 3), (try parse("2001:db8::/126")).hostCount()); try testing.expectEqual((@as(u129, 1) << 64) - 1, (try parse("2001:db8::/64")).hostCount()); // A `/127` is an inter-router link and a `/128` is one host. try testing.expectEqual(@as(u129, 2), (try parse("2001:db8::/127")).hostCount()); try testing.expectEqual(@as(u129, 1), (try parse("2001:db8::1/128")).hostCount()); } test firstHost { try testing.expect((try parse("2001:db8::/64")).firstHost().eql(try .parse("2001:db8::1"))); // At a `/127` the anycast address is not reserved, so the network address // is itself a host. try testing.expect((try parse("2001:db8::/127")).firstHost().eql(try .parse("2001:db8::"))); } test lastHost { // Always the last address, unlike IPv4, where it is the one before the // broadcast address. try testing.expect((try parse("2001:db8::/126")).lastHost().eql(try .parse("2001:db8::3"))); try testing.expect((try parse("2001:db8::1/128")).lastHost().eql(try .parse("2001:db8::1"))); } test hosts { var it = (try parse("2001:db8::/126")).hosts(); // `2001:db8::` is the Subnet-Router anycast address and is skipped; the // last address is not. try testing.expect(it.next().?.eql(try .parse("2001:db8::1"))); try testing.expect(it.next().?.eql(try .parse("2001:db8::2"))); try testing.expect(it.next().?.eql(try .parse("2001:db8::3"))); try testing.expectEqual(null, it.next()); // Both addresses of a `/127`. var link = (try parse("2001:db8::/127")).hosts(); try testing.expect(link.next().?.eql(try .parse("2001:db8::"))); try testing.expect(link.next().?.eql(try .parse("2001:db8::1"))); try testing.expectEqual(null, link.next()); } test containsNetwork { const outer = try parse("2001:db8::/32"); try testing.expect(outer.containsNetwork(try parse("2001:db8:1::/48"))); try testing.expect(outer.containsNetwork(outer)); // A shorter prefix is a larger network and cannot sit inside this one. try testing.expect(!outer.containsNetwork(try parse("2000::/3"))); } test overlaps { const network = try parse("2001:db8::/32"); // Two networks either nest or are disjoint, so overlapping is containment // one way or the other. try testing.expect(network.overlaps(try parse("2000::/3"))); try testing.expect(network.overlaps(try parse("2001:db8:1::/48"))); try testing.expect(!network.overlaps(try parse("2001:db9::/32"))); } test merge { // The two halves of a network become the network, twice over: the two // `/26`s make a `/25`, and that `/25` and the next one make the `/24`. var halves = [_]Ipv6Network{ try .parse("2001:db8::/34"), try .parse("2001:db8:4000::/34"), try .parse("2001:db8:8000::/33"), }; const folded = Ipv6Network.merge(&halves); try testing.expectEqual(@as(usize, 1), folded.len); try testing.expect(folded[0].eql(try .parse("2001:db8::/32"))); // A network inside another disappears, whichever order it arrived in. var nested = [_]Ipv6Network{ try .parse("2001:db8:1::/48"), try .parse("2001:db8::/32") }; const outer = Ipv6Network.merge(&nested); try testing.expectEqual(@as(usize, 1), outer.len); try testing.expect(outer[0].eql(try .parse("2001:db8::/32"))); // Networks that are neither nested nor halves of anything are all kept, // and come back sorted. // `2001:db9::/32` would be the wrong choice here: it is the sibling of // `2001:db8::/32` and folds into `2001:db8::/31`. var apart = [_]Ipv6Network{ try .parse("2001:dbc::/32"), try .parse("2001:db8::/32") }; const both = Ipv6Network.merge(&apart); try testing.expectEqual(@as(usize, 2), both.len); try testing.expect(both[0].eql(try .parse("2001:db8::/32"))); try testing.expect(both[1].eql(try .parse("2001:dbc::/32"))); // And the sibling really does fold, which is the claim above. var siblings = [_]Ipv6Network{ try .parse("2001:db9::/32"), try .parse("2001:db8::/32") }; try testing.expect(Ipv6Network.merge(&siblings)[0].eql(try .parse("2001:db8::/31"))); // Adjacent is not the same as joinable: these two touch and are not the // two halves of anything, because they are not the same size. var uneven = [_]Ipv6Network{ try .parse("2001:db8::/33"), try .parse("2001:db8:8000::/34") }; try testing.expectEqual(@as(usize, 2), Ipv6Network.merge(&uneven).len); // Duplicates collapse, since a network contains itself. var same = [_]Ipv6Network{ try .parse("2001:db8::/32"), try .parse("2001:db8::/32") }; try testing.expectEqual(@as(usize, 1), Ipv6Network.merge(&same).len); // Nothing at all is a valid input. var empty: [0]Ipv6Network = .{}; try testing.expectEqual(@as(usize, 0), Ipv6Network.merge(&empty).len); } test lessThan { // The order `merge` needs: a containing network ahead of what is inside // it, so that the sweep only ever has to look at the top of its stack. try testing.expect(lessThan({}, try .parse("2001:db8::/32"), try .parse("2001:db8:4000::/34"))); try testing.expect(!lessThan({}, try .parse("2001:db8:4000::/34"), try .parse("2001:db8::/32"))); } test join { // The two halves of a network, in either order. try testing.expect(Ipv6Network.join(try .parse("2001:db8::/34"), try .parse("2001:db8:4000::/34")).? .eql(try .parse("2001:db8::/33"))); try testing.expect(Ipv6Network.join(try .parse("2001:db8:4000::/34"), try .parse("2001:db8::/34")).? .eql(try .parse("2001:db8::/33"))); // The upper half and the lower half of the *next* network are adjacent // and are not halves of anything: the bit that tells halves apart is // already set in the first of them. try testing.expectEqual(null, Ipv6Network.join(try .parse("2001:db8:4000::/34"), try .parse("2001:db8:8000::/34"))); // Different sizes never join. try testing.expectEqual(null, Ipv6Network.join(try .parse("2001:db8::/33"), try .parse("2001:db8:8000::/34"))); // Nor does anything join into something wider than the address space. try testing.expectEqual(null, Ipv6Network.join(try .parse("::/0"), try .parse("::/0"))); } test eql { try testing.expect((try parse("2001:db8::/32")).eql(try parse("2001:0db8::/32"))); // The prefix length is part of the network, not just the address. try testing.expect(!(try parse("2001:db8::/32")).eql(try parse("2001:db8::/48"))); } test order { // A containing network sorts before the networks inside it. try testing.expectEqual(.lt, (try parse("2001:db8::/32")).order(try parse("2001:db8::/48"))); try testing.expectEqual(.lt, (try parse("2001:db8::/32")).order(try parse("2001:db9::/32"))); try testing.expectEqual(.eq, (try parse("2001:db8::/32")).order(try parse("2001:db8::/32"))); } test bufPrint { var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings("2001:db8::/32", try (try parse("2001:db8::/32")).bufPrint(&buffer)); var small: [4]u8 = undefined; try testing.expectError(error.NoSpaceLeft, (try parse("2001:db8::/32")).bufPrint(&small)); } test parseParts { // The two halves as the text gives them, before `init` or `initTruncate` // has had a say about the host bits. const parts = try parseParts("2001:db8::1/32"); try testing.expect(parts.address.eql(try .parse("2001:db8::1"))); try testing.expectEqual(@as(u8, 32), parts.prefix_len); // Text with no `/` at all is a single host. try testing.expectEqual(@as(u8, 128), (try parseParts("2001:db8::1")).prefix_len); } test netmaskInt { try testing.expectEqual(@as(u128, 0xffff_ffff) << 96, netmaskInt(32)); try testing.expectEqual(~@as(u128, 0), netmaskInt(128)); // A `/0` is the case the shift alone could not express: shifting a 128-bit // value by 128 is undefined, so zero is returned outright. try testing.expectEqual(@as(u128, 0), netmaskInt(0)); } test render { var buffer: [render_len]u8 = undefined; try testing.expectEqualStrings("2001:db8::/32", (try parse("2001:db8::/32")).render(&buffer)); try testing.expectEqualStrings("::/0", (try parse("::/0")).render(&buffer)); try testing.expectEqualStrings("2001:db8::1/128", (try parse("2001:db8::1/128")).render(&buffer)); }