// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Punycode (RFC 3492), the bootstring encoding IDNA uses to write a Unicode //! label as ASCII. //! //! This is pure arithmetic over code points and needs no Unicode tables, so it //! is always compiled in, even when the library is built without Unicode //! support. It encodes and decodes a single *label* — the `xn--` prefix and //! the splitting of a domain on `.` belong to IDNA, in `idna.zig`. const std = @import("std"); // RFC 3492 §5. const base = 36; const tmin = 1; const tmax = 26; const skew = 38; const damp = 700; const initial_bias = 72; const initial_n: u32 = 128; const delimiter = '-'; pub const EncodeError = error{Overflow} || std.mem.Allocator.Error; pub const DecodeError = error{ /// A digit outside the basic code point set, or a stray delimiter. InvalidInput, /// The decoded value would leave the Unicode range, or the integer /// arithmetic overflowed. RFC 3492 §6.4 requires rejecting both. Overflow, } || std.mem.Allocator.Error; /// RFC 3492 §6.1. fn adapt(delta_in: u32, numpoints: u32, firsttime: bool) u32 { var delta = if (firsttime) delta_in / damp else delta_in / 2; delta += delta / numpoints; var k: u32 = 0; while (delta > ((base - tmin) * tmax) / 2) { delta /= base - tmin; k += base; } return k + (((base - tmin + 1) * delta) / (delta + skew)); } /// `a`-`z` and `0`-`9` map to 0..35. fn decodeDigit(c: u8) ?u32 { return switch (c) { 'A'...'Z' => c - 'A', 'a'...'z' => c - 'a', '0'...'9' => c - '0' + 26, else => null, }; } fn encodeDigit(d: u32) u8 { std.debug.assert(d < base); return if (d < 26) @intCast('a' + d) else @intCast('0' + d - 26); } /// Encode one label's code points as Punycode, without the `xn--` prefix. /// /// The output is the basic (ASCII) code points, then a delimiter if there were /// any, then the encoded non-ASCII ones. An all-ASCII input still gets its /// trailing delimiter, which is what lets `decode` find the boundary. pub fn encode(alloc: std.mem.Allocator, input: []const u21) EncodeError![]u8 { var out: std.ArrayList(u8) = .empty; errdefer out.deinit(alloc); var basic_count: u32 = 0; for (input) |cp| { if (cp < 0x80) { try out.append(alloc, @intCast(cp)); basic_count += 1; } } if (basic_count > 0) try out.append(alloc, delimiter); var n = initial_n; var delta: u32 = 0; var bias: u32 = initial_bias; var handled = basic_count; while (handled < input.len) { // The next code point to encode is the smallest one still >= n. var m: u32 = std.math.maxInt(u32); for (input) |cp| { const v: u32 = cp; if (v >= n and v < m) m = v; } const advance = std.math.mul(u32, m - n, handled + 1) catch return error.Overflow; delta = std.math.add(u32, delta, advance) catch return error.Overflow; n = m; for (input) |cp| { const v: u32 = cp; if (v < n) { delta = std.math.add(u32, delta, 1) catch return error.Overflow; } else if (v == n) { var q = delta; var k: u32 = base; while (true) : (k += base) { const t = if (k <= bias) tmin else if (k >= bias + tmax) tmax else k - bias; if (q < t) break; try out.append(alloc, encodeDigit(t + ((q - t) % (base - t)))); q = (q - t) / (base - t); } try out.append(alloc, encodeDigit(q)); bias = adapt(delta, handled + 1, handled == basic_count); delta = 0; handled += 1; } } delta += 1; n += 1; } return out.toOwnedSlice(alloc); } /// Decode one Punycode label, without the `xn--` prefix, into code points. pub fn decode(alloc: std.mem.Allocator, input: []const u8) DecodeError![]u21 { var out: std.ArrayList(u21) = .empty; errdefer out.deinit(alloc); // Everything before the last delimiter is literal ASCII. var read: usize = 0; if (std.mem.lastIndexOfScalar(u8, input, delimiter)) |i| { for (input[0..i]) |c| { if (c >= 0x80) return error.InvalidInput; try out.append(alloc, c); } read = i + 1; } var n = initial_n; var i: u32 = 0; var bias: u32 = initial_bias; while (read < input.len) { const oldi = i; var w: u32 = 1; var k: u32 = base; while (true) : (k += base) { if (read >= input.len) return error.InvalidInput; const digit = decodeDigit(input[read]) orelse return error.InvalidInput; read += 1; const add = std.math.mul(u32, digit, w) catch return error.Overflow; i = std.math.add(u32, i, add) catch return error.Overflow; const t = if (k <= bias) tmin else if (k >= bias + tmax) tmax else k - bias; if (digit < t) break; w = std.math.mul(u32, w, base - t) catch return error.Overflow; } const len: u32 = @intCast(out.items.len + 1); bias = adapt(i - oldi, len, oldi == 0); n = std.math.add(u32, n, i / len) catch return error.Overflow; i %= len; if (n > 0x10FFFF or (n >= 0xD800 and n <= 0xDFFF)) return error.Overflow; try out.insert(alloc, i, @intCast(n)); i += 1; } return out.toOwnedSlice(alloc); }