Algorithm Search⌘K

Algorithmcore

Punycode

Also called Bootstring encoding.

Encode a Unicode string as ASCII letters, digits and hyphens. The basic characters are copied, and the others are written as sorted insertions with deltas in a variable-length base 36 code.

Time
Θ(N^2) worstΘ(N) best
Space
O(N) extra
Where
N = the number of code points of the string
Properties
deterministicofflineiterative

Punycode writes a string of Unicode code points as a string of ASCII letters, digits and hyphens, so that a domain name such as bücher.example can travel through the DNS, which only allows those characters in host names. It copies the ASCII characters first and then describes where each other character goes and what its value is, as a sequence of insertions sorted by value. Each insertion is one number, a delta from the one before, and the numbers are written in a variable-length base 36 code whose thresholds adapt to the size of the recent deltas. Adam Costello defined it in RFC 3492 (2003) as an instance of a general method called Bootstring.

In plain words

Think of the name "bücher". The plain letters b, c, h, e and r can go into the result as they are. Only ü needs a description, and that description must use plain letters too.

Punycode writes "bcher", a hyphen, and then a short code for the instruction "put the character ü at place 1". It joins the value of ü and its place into one number, so that the description is a single number.

When a name has many special characters, Punycode puts them in order of their value and writes each one as the difference from the one before. These differences are usually small, so they take few letters. The letters work like digits in base 36, with a rule that tells where each number ends. So "bücher" becomes "bcher-kva", and with the prefix "xn--" it is the host name label "xn--bcher-kva".

The problem

The input is a string ss of NN scalar values. A code point below 80 is basic. The output is a string of basic code points from which ss can be recovered, and the decoder does that recovery. It must reject inputs that no string encodes to.

The parameters of section 5 of RFC 3492 are: base 36, tmin⁡=1t_{\min} = 1, tmax⁡=26t_{\max} = 26, skew 38, damp 700, initial bias 72 and initial nn 128. The digit values 0 to 25 are the letters a to z, in either case, and 26 to 35 are the digits 0 to 9. The delimiter is "-".

The threshold for the digit at position k=36,72,108,…k = 36, 72, 108, \ldots of a number is

T(k,bias)={1if k≤bias,26if k≥bias+26,k−biasotherwise.T(k, bias) = \begin{cases} 1 & \text{if } k \le bias, \\ 26 & \text{if } k \ge bias + 26, \\ k - bias & \text{otherwise.} \end{cases}

ADAPT(δ,count,first)(\delta, count, first), from section 6.1, divides δ\delta by 700 if firstfirst and by 2 otherwise, adds δdiv⁡count\delta \operatorname{div} count, and then returns 36k′+⌊36δ′/(δ′+38)⌋36 k' + \lfloor 36 \delta' / (\delta' + 38) \rfloor, where k′k' counts how many times δ\delta had to be divided by 35 to get a value δ′\delta' of at most 455.

The algorithm

  1. PUNYCODE-ENCODE(s)
  2. 1out <- the basic code points of s, in order
  3. 2b <- |out|; h <- b; if b > 0 then append "-" to out
  4. 3n <- 128; delta <- 0; bias <- 72
  5. 4while h < |s| do
  6. 5m <- the least code point of s that is at least n
  7. 6delta <- delta + (m - n) * (h + 1); n <- m
  8. 7for each code point c of s, in order do
  9. 8if c < n then delta <- delta + 1
  10. 9if c = n then
  11. 10q <- delta; k <- 36; t <- T(k, bias)
  12. 11while q >= t do append DIGIT(t + (q - t) mod (36 - t)); q <- (q - t) div (36 - t); k <- k + 36; t <- T(k, bias)
  13. 12append DIGIT(q)
  14. 13bias <- ADAPT(delta, h + 1, h = b); delta <- 0; h <- h + 1
  15. 14delta <- delta + 1; n <- n + 1
  16. PUNYCODE-DECODE(p)
  17. 15out <- the code points of p before its last "-", or nothing if that "-" is not after position 0; pos <- the index of the first code point after them and the "-"
  18. 16n <- 128; i <- 0; bias <- 72
  19. 17while pos < |p| do
  20. 18oldi <- i; w <- 1; k <- 36
  21. 19loop: fail if pos = |p|; d <- VALUE(p[pos]); pos <- pos + 1
  22. 20i <- i + d * w; t <- T(k, bias)
  23. 21if d < t then exit the loop; w <- w * (36 - t); k <- k + 36
  24. 22bias <- ADAPT(i - oldi, |out| + 1, oldi = 0)
  25. 23n <- n + i div (|out| + 1); i <- i mod (|out| + 1)
  26. 24insert n into out at index i; i <- i + 1

The encoder returns outout when the loop of line L4 ends, and the decoder returns outout when the loop of line L17 ends.

Insertion unsort coding (section 3.2). The decoder keeps a state (n,i)(n, i): the value of the next code point to insert and the index where it goes. One delta moves the state forward. The index runs fastest and the value slowest, so a delta of δ\delta from (n,i)(n, i) in a string of hh code points means "skip δ\delta places in the list of all pairs (value, index), where each value has h+1h + 1 indexes". Line L23 turns the skipped count back into a value and an index. The encoder produces the same count by scanning ss once per value (lines L7 to L9) and counting the code points that are already in the decoder's string.

Generalized variable-length integers (section 3.3). A delta is written least significant digit first. A digit below its threshold tt is the last digit, so the code needs no separator. The weight of each digit is the product of 36−t36 - t over the earlier digits.

Bias adaptation (section 3.4). After each delta, ADAPT sets the bias so that the thresholds fit the size of the next delta. The first delta is usually large, since it carries the distance from 128 to the first value, so it is damped by 700 instead of 2.

Checks. The decoder fails on a non-basic code point before the delimiter, on a character that is not a digit, on input that ends inside a number (line L19), and on an overflow of 32-bit unsigned integers (section 6.4). The implementation also rejects a decoded value that is basic, a surrogate or above 10FFFF.

Example

Encode "bücher". Line L1 gives "bcher", so b=h=5b = h = 5, and line L2 appends "-". Line L5 finds m=FCm = \mathtt{FC} (ü), and line L6 sets δ=(252−128)⋅6=744\delta = (252 - 128) \cdot 6 = 744. The scan meets b, which is below FC, so δ=745\delta = 745, and then ü.

digit position kk threshold tt qq digit value character
36 1 745 1+744 mod 35=101 + 744 \bmod 35 = 10 k
72 1 744div⁡35=21744 \operatorname{div} 35 = 21 1+20 mod 35=211 + 20 \bmod 35 = 21 v
108 26 20div⁡35=020 \operatorname{div} 35 = 0 0 a

The bias is 72 for the first delta, so the thresholds are 1, 1 and 26. The output is "bcher-kva".

Decode it. Line L15 gives "bcher". The digits k, v and a have the values 10, 21 and 0 and the weights 1, 35 and 35235^2, so i=10+21⋅35=745i = 10 + 21 \cdot 35 = 745, and a stops the number because 0<260 < 26. Line L23 sets n=128+745div⁡6=252n = 128 + 745 \operatorname{div} 6 = 252 and i=745 mod 6=1i = 745 \bmod 6 = 1, and line L24 inserts U+00FC at index 1. The result is "bücher". The tests also check "münchen" (mnchen-3ya), "mañana" (maana-pta) and the 12 samples of section 7.1 that have no mixed-case annotation.

Correctness

The proof in proofs/correctness.md has three steps. First, if the decoder inserts the non-basic code points in the order of (value, position), each at the index equal to the number of code points already placed before it, it rebuilds ss. Second, the delta that line L10 writes is exactly the one that moves the decoder state from one insertion to the next: line L6 counts the values skipped, times the number of indexes per value, and the scan counts the placed code points before each position. Third, the variable-length code of lines L10 to L12 and lines L18 to L21 is a bijection, as long as both sides use the same thresholds, and they do, because they call ADAPT with the same arguments. Digits are never "-", so the last "-" of the output separates the basic code points from the digits.

Proof: Punycode decoding inverts Punycode encodingfull

Claim. Let ss be a string of NN scalar values, bb of them basic (below U+0080). If PUNYCODE-ENCODE(s)(s) (lines L1 to L14) does not stop with an overflow, it stops, its output consists of basic code points only, and PUNYCODE-DECODE (lines L15 to L24) applied to it stops and returns ss. So the encoding is injective on these strings.

Notation. Number the positions of ss from 0. Order the N−bN - b non-basic positions by (value, position), and call them insertion 1,…,N−b1, \ldots, N - b. Insertion tt is at position post\mathrm{pos}_t and has value ntn_t. Let ht=b+t−1h_t = b + t - 1, the number of code points already placed before insertion tt, and let

pt=#{ q<post:s[q]≤nt }.p_t = \#\{\, q < \mathrm{pos}_t : s[q] \le n_t \,\}.

Lemma 1 (what the decoder builds). Suppose the decoder starts with the basic code points of ss in order and, for t=1,2,…t = 1, 2, \ldots, inserts ntn_t at index ptp_t. Then after insertion tt its string is the subsequence of ss made of the basic code points and insertions 11 to tt. At the end it is ss.

Proof. By induction on tt. Before insertion tt, the placed code points are those of ss with value below ntn_t, and those with value ntn_t at positions before post\mathrm{pos}_t, in the order of ss. Exactly ptp_t of them lie before post\mathrm{pos}_t in ss, so inserting ntn_t at index ptp_t puts it in its place. □\square

The decoder state. The decoder keeps a pair (n,i)(n, i). After insertion tt it has (nt,pt+1)(n_t, p_t + 1), and its string has ht+1h_t + 1 code points, so an insertion index is one of 0,…,ht+10, \ldots, h_t + 1, which is ht+1+1h_{t+1} + 1 choices. Lines L18 to L21 read a number δ\delta and add it to ii. Line L23 carries idiv⁡(ht+1+1)i \operatorname{div} (h_{t+1} + 1) into nn and keeps i mod (ht+1+1)i \bmod (h_{t+1} + 1), and line L24 inserts nn at index ii. So insertion t+1t + 1 lands at (nt+1,pt+1)(n_{t+1}, p_{t+1}) exactly when

δt+1=(nt+1−nt)(ht+1+1)+pt+1−pt−1,(1)\delta_{t+1} = (n_{t+1} - n_t)(h_{t+1} + 1) + p_{t+1} - p_t - 1, \qquad (1)

and the first insertion lands at (n1,p1)(n_1, p_1) from the start state (128,0)(128, 0) exactly when δ1=(n1−128)(b+1)+p1\delta_1 = (n_1 - 128)(b + 1) + p_1.

Lemma 2 (the encoder writes these deltas). The value of δ\delta that line L10 writes for insertion tt is δt\delta_t as above.

Proof. The encoder handles the values mm in increasing order (line L5 takes the least value not below nn). For each mm it scans all of ss (line L7). It adds 1 to δ\delta for each code point below mm (line L8), writes δ\delta and resets it to 0 at each code point equal to mm (line L9), and adds 1 at the end of the scan (line L14). Before the scan it adds (m−n)(h+1)(m - n)(h + 1), where nn is the old value plus 1 and hh counts the code points placed so far (line L6).

First insertion: δ=(n1−128)(b+1)\delta = (n_1 - 128)(b + 1), plus one for each code point below n1n_1 before pos1\mathrm{pos}_1. No value of ss lies in 128…n1−1128 \ldots n_1 - 1, so these are the basic code points before pos1\mathrm{pos}_1, and their count is p1p_1.

Insertion t+1t + 1 with nt+1=ntn_{t+1} = n_t: since insertion tt, the scan has passed the positions strictly between post\mathrm{pos}_t and post+1\mathrm{pos}_{t+1}. None of them has the value ntn_t, so δ\delta counts those with a value below ntn_t. That is pt+1−pt−1p_{t+1} - p_t - 1, because the extra −1-1 removes position post\mathrm{pos}_t itself, which pt+1p_{t+1} counts and ptp_t does not. The first term of (1) is 0.

Insertion t+1t + 1 with nt+1=m>ntn_{t+1} = m > n_t: insertion tt is the last one of value ntn_t. The rest of that scan adds r=#{ q>post:s[q]<nt }r = \#\{\, q > \mathrm{pos}_t : s[q] < n_t \,\}, line L14 adds 1, line L6 adds (m−nt−1)(ht+1+1)(m - n_t - 1)(h_{t+1} + 1), and the new scan adds #{ q<post+1:s[q]<m }=pt+1\#\{\, q < \mathrm{pos}_{t+1} : s[q] < m \,\} = p_{t+1}. All code points of value at most ntn_t are placed, so ht+1=pt+1+rh_{t+1} = p_t + 1 + r. The total is r+1+(m−nt−1)(ht+1+1)+pt+1r + 1 + (m - n_t - 1)(h_{t+1} + 1) + p_{t+1}, and with r=ht+1−pt−1r = h_{t+1} - p_t - 1 this equals (1). □\square

Lemma 3 (variable-length integers). Fix thresholds t0,t1,…t_0, t_1, \ldots with 1≤tj≤261 \le t_j \le 26, and let w0=1w_0 = 1 and wj+1=wj(36−tj)w_{j+1} = w_j (36 - t_j). Lines L10 to L12 write q≥0q \ge 0 as digits d0,…,drd_0, \ldots, d_r with dj≥tjd_j \ge t_j for j<rj < r, dr<trd_r < t_r, and q=∑jdjwjq = \sum_j d_j w_j. Lines L18 to L21 read these digits back, stop after drd_r, and get qq.

Proof. Let q0=qq_0 = q. While qj≥tjq_j \ge t_j, the encoder writes dj=tj+(qj−tj) mod (36−tj)d_j = t_j + (q_j - t_j) \bmod (36 - t_j), which lies in tj…35t_j \ldots 35, and sets qj+1=(qj−tj)div⁡(36−tj)q_{j+1} = (q_j - t_j) \operatorname{div} (36 - t_j). Then qj=dj+(36−tj) qj+1q_j = d_j + (36 - t_j)\, q_{j+1}. Also qj+1<qjq_{j+1} < q_j, so the loop stops, with a last digit dr=qr<trd_r = q_r < t_r. Unfolding gives q=∑jdjwjq = \sum_j d_j w_j. The decoder adds djwjd_j w_j and stops at the first digit below its threshold, which is drd_r. □\square

Both sides compute the thresholds from kk and the bias in the same way. The bias is the initial bias for the first delta. After each delta, both sides call ADAPT with the same arguments: the delta, the number of code points after the insertion (h+1h + 1 in line L13, the output length plus 1 in line L22), and a flag that is true only for the first delta (h=bh = b in the encoder, oldi=0\mathit{oldi} = 0 in the decoder, since later deltas start from i=pt+1≥1i = p_t + 1 \ge 1). So by induction the thresholds agree for every delta. Digits map to the characters a to z and 0 to 9, a bijection on 0…350 \ldots 35, and none of them is the delimiter "-".

Proof of the claim. The output of the encoder is the basic code points of ss, then "-" if b>0b > 0, then the digits. Digits are never "-", so the last "-" of the output is the one after the basic code points, and if b=0b = 0 the output has no "-". Line L15 therefore recovers exactly the basic code points. By Lemma 3, the decoder reads exactly the deltas that the encoder wrote, and by Lemma 2 and (1) each delta brings the decoder state to (nt,pt)(n_t, p_t). By Lemma 1 the decoder then returns ss. The values ntn_t are non-basic scalar values, so the checks after line L23 never reject them.

Termination. Each pass of the loop of line L4 handles at least one code point, because line L5 picks a value that occurs in ss, so hh grows and the loop stops when h=Nh = N. The digit loop stops by Lemma 3. The decoder moves pos\mathit{pos} forward with each digit it reads and stops when the input ends. With the overflow checks of RFC 3492 section 6.4, every intermediate value fits in 32 bits, and if one would not, the procedure stops with an error instead. ■\blacksquare

Complexity

In the word-RAM model, with NN code points of which N−bN - b are not basic, the encoder does one scan of ss for each distinct non-basic value, plus a scan in line L5 to find it, so it takes O(N(N−b+1))O(N (N - b + 1)) time. Each delta fits in 32 bits, and line L11 divides it by at least 10 for each digit, so it has at most 11 digits. The decoder inserts into an array, which costs O(N)O(N) per insertion. Both are Θ(N2)\Theta(N^2) in the worst case and Θ(N)\Theta(N) when all code points are basic.

claim value
encoding time O(N(N−b+1))O(N (N - b + 1))
decoding time O(N(N−b+1))O(N (N - b + 1)) with an array
digits per delta at most 11 for 32-bit deltas

A DNS label has at most 63 octets, so NN is small in practice, and the quadratic bound does not matter there.

Properties

  • Injective. Different strings give different outputs, and the decoder inverts the encoder.
  • Basic code points first. The ASCII part of the label stays readable, as in "bcher-kva".
  • Not unique on input to the decoder. The decoder accepts digits in either case, so "maana-PTA" also decodes to "mañana". A label must be compared after a round trip through the decoder and the encoder, or in lowercase.
  • Compact. Sorted insertions with adaptive thresholds give short outputs for text in one script, because the values of such text lie close together.

Variants and improvements

  • Bootstring. Section 3 defines the method for any set of parameters: the base, the thresholds, the damping and the initial values. Punycode is one choice of them, tuned for domain names.
  • Mixed-case annotation. Appendix A of RFC 3492 lets the case of each final digit carry a hint about the case of the code point. IDNA does not use it, and the implementation writes lowercase digits.
  • Faster decoding. A balanced tree or a rope for outout makes each insertion O(log⁡N)O(\log N), which makes decoding O(Nlog⁡N)O(N \log N) besides the digit reading.

When to use it

Use Punycode to turn an internationalized domain name label into the "xn--" form that DNS, TLS certificates and mail headers carry. Punycode is only the last step of that process. IDNA2008 (RFC 5891) or UTS 46 first map and check the label, with normalization to NFC and, in UTS 46, case folding, and then each label is encoded. For general text in ASCII channels, use UTF-8 with a transfer encoding instead. Punycode is not designed for long strings.

Pitfalls

  • Overflow. A crafted label can make ii or ww exceed 32 bits. The decoder must check before each multiplication and addition, as section 6.4 shows. The test test_overflow_is_detected checks this.
  • Truncated numbers. A label that ends with a digit at or above its threshold is invalid. The test test_bad_input checks this and other bad inputs.
  • A delimiter at the start. If the only "-" is at position 0, there are no basic code points, and the "-" is read as a digit, which fails. "-" itself is not a valid label.
  • Case. Uppercase and lowercase digits have the same value, but basic code points keep their case. The test test_decoder_accepts_uppercase_digits checks this.
  • Skipping the IDNA checks. Encoding a label without the mapping and validity checks of IDNA allows labels that look like other labels. See confusable detection. Python's "idna" codec implements the older IDNA2003, not IDNA2008, so the tests use the "punycode" codec as the oracle.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

punycode.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/punycode/. The authors are listed in prov/S9VM2F.jsonl.

"""Punycode, the instance of Bootstring in RFC 3492 (Costello, March 2003).

encode and decode follow the procedures of RFC 3492 section 6.2 and 6.3, with the overflow
checks of section 6.4 for 32-bit unsigned integers. Mixed-case annotation (Appendix A) is
not done: the encoder writes lowercase digits and the decoder accepts both cases.
"""

BASE = 36
TMIN = 1
TMAX = 26
SKEW = 38
DAMP = 700
INITIAL_BIAS = 72
INITIAL_N = 128
DELIMITER = "-"
MAXINT = 2**32 - 1  # the integers of the RFC sample code are 32-bit unsigned


class PunycodeError(ValueError):
    pass


def adapt(delta: int, numpoints: int, firsttime: bool) -> int:
    """Bias adaptation, RFC 3492 section 6.1."""
    delta = delta // DAMP if firsttime else delta // 2
    delta += delta // numpoints
    k = 0
    while delta > ((BASE - TMIN) * TMAX) // 2:
        delta //= BASE - TMIN
        k += BASE
    return k + (BASE - TMIN + 1) * delta // (delta + SKEW)


def digit_value(ch: str) -> int:
    o = ord(ch)
    if 0x30 <= o <= 0x39:
        return o - 0x30 + 26  # 0..9 have the values 26..35
    if 0x41 <= o <= 0x5A:
        return o - 0x41
    if 0x61 <= o <= 0x7A:
        return o - 0x61
    raise PunycodeError(f"bad digit {ch!r}")


def digit_char(d: int) -> str:
    return chr(d + 0x61) if d < 26 else chr(d - 26 + 0x30)


def threshold(k: int, bias: int) -> int:
    return TMIN if k <= bias else TMAX if k >= bias + TMAX else k - bias


def encode(s: str) -> str:
    """Encode a str of code points as Punycode (no "xn--" prefix)."""
    cps = [ord(ch) for ch in s]
    out = [ch for ch in s if ord(ch) < 0x80]  # @line L1
    b = h = len(out)  # @line L2
    if b > 0:
        out.append(DELIMITER)
    n, delta, bias = INITIAL_N, 0, INITIAL_BIAS  # @line L3
    while h < len(cps):  # @line L4
        m = min(c for c in cps if c >= n)  # @line L5
        if (m - n) * (h + 1) > MAXINT - delta:
            raise PunycodeError("overflow")
        delta += (m - n) * (h + 1)  # @line L6
        n = m
        for c in cps:  # @line L7
            if c < n:  # @line L8
                delta += 1
                if delta > MAXINT:
                    raise PunycodeError("overflow")
            if c == n:  # @line L9
                q = delta  # @line L10
                k = BASE
                while True:
                    t = threshold(k, bias)
                    if q < t:
                        break
                    out.append(digit_char(t + (q - t) % (BASE - t)))  # @line L11
                    q = (q - t) // (BASE - t)
                    k += BASE
                out.append(digit_char(q))  # @line L12
                bias = adapt(delta, h + 1, h == b)  # @line L13
                delta = 0
                h += 1
        delta += 1  # @line L14
        n += 1
    return "".join(out)


def decode(p: str) -> str:
    """Decode Punycode (no "xn--" prefix) to a str. Raises PunycodeError on bad input."""
    j = p.rfind(DELIMITER)
    basic = p[:j] if j > 0 else ""  # @line L15
    if any(ord(ch) >= 0x80 for ch in basic):
        raise PunycodeError("non-basic code point before the delimiter")
    out = [ord(ch) for ch in basic]
    pos = j + 1 if j > 0 else 0
    n, i, bias = INITIAL_N, 0, INITIAL_BIAS  # @line L16
    while pos < len(p):  # @line L17
        oldi, w, k = i, 1, BASE  # @line L18
        while True:
            if pos >= len(p):
                raise PunycodeError("truncated input")
            digit = digit_value(p[pos])  # @line L19
            pos += 1
            if digit > (MAXINT - i) // w:
                raise PunycodeError("overflow")
            i += digit * w  # @line L20
            t = threshold(k, bias)
            if digit < t:  # @line L21
                break
            if w > MAXINT // (BASE - t):
                raise PunycodeError("overflow")
            w *= BASE - t
            k += BASE
        bias = adapt(i - oldi, len(out) + 1, oldi == 0)  # @line L22
        if i // (len(out) + 1) > MAXINT - n:
            raise PunycodeError("overflow")
        n += i // (len(out) + 1)  # @line L23
        i %= len(out) + 1
        if n < 0x80 or 0xD800 <= n <= 0xDFFF or n > 0x10FFFF:
            raise PunycodeError(f"decoded value {n:#x} is basic or not a scalar value")
        out.insert(i, n)  # @line L24
        i += 1
    return "".join(map(chr, out))


def to_ascii_label(label: str) -> str:
    """The ACE form of one label: "xn--" plus Punycode when the label is not all ASCII.

    This is only the encoding step. IDNA2008 (RFC 5891) and UTS 46 also map and check the
    label before this step; this function does neither.
    """
    if all(ord(ch) < 0x80 for ch in label):
        return label
    return "xn--" + encode(label)
test_punycode.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/punycode/. The authors are listed in prov/S9VM2F.jsonl.

# The oracle is Python's "punycode" codec (RFC 3492). Written against Python 3.14.
# Never use the "idna" codec as an oracle: it implements IDNA2003, not IDNA2008.

import random

from punycode import PunycodeError, adapt, decode, encode, to_ascii_label

# RFC 3492, section 7.1 (Sample strings), samples (A) to (C) and (G) to (S), in the format
# "label: code points: Punycode". The ACE prefix is omitted, as in the RFC.
RFC_SAMPLES = """\
(A) Arabic (Egyptian): u+0644 u+064A u+0647 u+0645 u+0627 u+0628 u+062A u+0643 u+0644 u+0645 u+0648 u+0634 u+0639 u+0631 u+0628 u+064A u+061F: egbpdaj6bu4bxfgehfvwxn
(B) Chinese (simplified): u+4ED6 u+4EEC u+4E3A u+4EC0 u+4E48 u+4E0D u+8BF4 u+4E2D u+6587: ihqwcrb4cv8a8dqg056pqjye
(C) Chinese (traditional): u+4ED6 u+5011 u+7232 u+4EC0 u+9EBD u+4E0D u+8AAA u+4E2D u+6587: ihqwctvzc91f659drss3x8bo0yb
(G) Japanese (kanji and hiragana): u+306A u+305C u+307F u+3093 u+306A u+65E5 u+672C u+8A9E u+3092 u+8A71 u+3057 u+3066 u+304F u+308C u+306A u+3044 u+306E u+304B: n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa
(L) 3<nen>B<gumi><kinpachi><sensei>: u+0033 u+5E74 U+0042 u+7D44 u+91D1 u+516B u+5148 u+751F: 3B-ww4c5e180e575a65lsy2b
(M) <amuro><namie>-with-SUPER-MONKEYS: u+5B89 u+5BA4 u+5948 u+7F8E u+6075 u+002D u+0077 u+0069 u+0074 u+0068 u+002D U+0053 U+0055 U+0050 U+0045 U+0052 u+002D U+004D U+004F U+004E U+004B U+0045 U+0059 U+0053: -with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n
(N) Hello-Another-Way-<sorezore><no><basho>: U+0048 u+0065 u+006C u+006C u+006F u+002D U+0041 u+006E u+006F u+0074 u+0068 u+0065 u+0072 u+002D U+0057 u+0061 u+0079 u+002D u+305D u+308C u+305E u+308C u+306E u+5834 u+6240: Hello-Another-Way--fc4qua05auwb3674vfr0b
(O) <hitotsu><yane><no><shita>2: u+3072 u+3068 u+3064 u+5C4B u+6839 u+306E u+4E0B u+0032: 2-u9tlzr9756bt3uc0v
(P) Maji<de>Koi<suru>5<byou><mae>: U+004D u+0061 u+006A u+0069 u+3067 U+004B u+006F u+0069 u+3059 u+308B u+0035 u+79D2 u+524D: MajiKoi5-783gue6qz075azm5e
(Q) <pafii>de<runba>: u+30D1 u+30D5 u+30A3 u+30FC u+0064 u+0065 u+30EB u+30F3 u+30D0: de-jg4avhby1noc0d
(R) <sono><supiido><de>: u+305D u+306E u+30B9 u+30D4 u+30FC u+30C9 u+3067: d9juau41awczczp
(S) -> $1.00 <-: u+002D u+003E u+0020 u+0024 u+0031 u+002E u+0030 u+0030 u+0020 u+003C u+002D: -> $1.00 <--
"""


def parse_samples():
    for line in RFC_SAMPLES.splitlines():
        head, rest = line.split(": u+", 1) if ": u+" in line else line.split(": U+", 1)
        cps, puny = ("u+" + rest).rsplit(": ", 1)
        yield head, "".join(chr(int(x[2:], 16)) for x in cps.split()), puny


def test_rfc_samples() -> None:
    samples = list(parse_samples())
    assert len(samples) == 12
    for head, s, puny in samples:
        assert encode(s) == puny, head
        assert decode(puny) == s, head


def test_check_values() -> None:
    for word, puny in [("bücher", "bcher-kva"), ("münchen", "mnchen-3ya"), ("ü", "tda"), ("mañana", "maana-pta")]:
        assert encode(word) == puny
        assert decode(puny) == word
    assert to_ascii_label("mañana") == "xn--maana-pta"
    assert to_ascii_label("example") == "example"


def test_decoder_accepts_uppercase_digits() -> None:
    assert decode("maana-PTA") == "mañana"
    # The basic code points keep their case; the inserted one is the code point of the delta.
    assert decode("MAANA-pta") == "MA" + "ñ" + "ANA"


def test_adapt_first_steps() -> None:
    # "ü" alone: delta = (0xFC - 0x80) * 1 = 124, so the bias after the first insertion is
    # adapt(124, 1, True) = 0 + 36 * 0 // 38 = 0.
    assert adapt(124, 1, True) == 0
    assert adapt(0, 1, False) == 0


def test_round_trip_against_codec() -> None:
    rng = random.Random(1)
    pools = [range(0x61, 0x7B), range(0xC0, 0x180), range(0x3040, 0x30A0), range(0x4E00, 0x4F00),
             range(0x1F600, 0x1F650), range(0x30, 0x3A)]
    for _ in range(1500):
        s = "".join(chr(rng.choice(rng.choice(pools))) for _ in range(rng.randrange(1, 15)))
        p = encode(s)
        assert p == s.encode("punycode").decode("ascii")
        assert decode(p) == s
        assert all(ch.isascii() and (ch.isalnum() or ch == "-") for ch in p) or not s.isalnum()


def test_bad_input() -> None:
    # A non-basic code point, a lone delimiter (decoded as a digit), and two inputs that end
    # inside a variable-length integer (the last digit is not below its threshold).
    for bad in ["a-é", "-", "abc-9", "b-z"]:
        try:
            decode(bad)
            raise AssertionError(f"{bad!r} must be rejected")
        except PunycodeError:
            pass


def test_overflow_is_detected() -> None:
    try:
        decode("99999999999999")
        raise AssertionError("expected overflow")
    except PunycodeError:
        pass

History

The IETF worked on internationalized domain names in the early 2000s, and several ASCII-compatible encodings were proposed. Adam Costello's Punycode was chosen, and it was published in March 2003 as RFC 3492, together with RFC 3490 (IDNA) and RFC 3491 (Nameprep). The revised protocol of 2010, IDNA2008 (RFC 5890 to RFC 5894), replaced Nameprep with new rules but kept Punycode and the "xn--" prefix.

References

  1. A. Costello, Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA), RFC 3492, March 2003, Section 3 (Bootstring description: 3.1 basic code point segregation, 3.2 insertion unsort coding, 3.3 generalized variable-length integers, 3.4 bias adaptation), Section 5 (parameter values), Section 6 (6.1 bias adaptation function, 6.2 decoding procedure, 6.3 encoding procedure, 6.4 overflow handling) and Section 7.1 (sample strings)
  2. Python documentation, codecs, Text Encodings (the punycode codec) and encodings.idna

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • at least three sources
  • a scene preset for the example