Programming Search⌘K

Taskcore

Normalize Unicode text

Also called Unicode normalization, NFC, NFD, NFKC, NFKD, canonical equivalence, precomposed character, decomposed character.

Put text in one normalization form, NFC or NFD, so that the 2 ways to write a letter with an accent give the same code points.

Task

Put a string in a normalization form. The letter U+00E9 has 2 forms: the one code point U+00E9, and e with U+0301 COMBINING ACUTE ACCENT. They are canonical equivalents, which "represent the same abstract character, and which when correctly displayed should always have the same visual appearance and behavior"1. But a compare of the code points finds 2 different strings.

The function normalize(s, form) returns s in one of 2 forms:

Form Rule caf U+00E9 cafe U+0301
NFD "Canonical Decomposition"1 cafe U+0301 cafe U+0301
NFC "Canonical Decomposition, followed by Canonical Composition"1 caf U+00E9 caf U+00E9

After the same form, the 2 strings are equal. NFKD and NFKC also use compatibility equivalence, which is "a weaker type of equivalence"1. Those forms can change the text, so this task does not use them.

The contract has a small set of code points: U+0000 to U+00FF, and the marks U+0300, U+0301, U+0302 and U+0308 after one of the vowels a, e, i, o, u, A, E, I, O and U. For this set, the full rule is a table of 40 pairs: each vowel with each mark, and its composite from U+00C0 to U+00FC. A full normalizer also puts the marks in the canonical order, and it has many more pairs1.

Solutions

Language Normalize
Python unicodedata.normalize(form, s)
JavaScript, TypeScript s.normalize(form)
Java Normalizer.normalize(s, Normalizer.Form.valueOf(form))
C# s.Normalize(NormalizationForm.FormC) or FormD
Go the table; the module golang.org/x/text/unicode/norm has the full rule
Rust, C, C++, Bash the table
  • Python. For unicodedata.normalize, "Valid values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'"2.
  • JavaScript. For the argument of normalize, "If omitted or undefined, "NFC" is used"3.
  • Java. Normalizer "transforms Unicode text into an equivalent composed or decomposed form, allowing for easier sorting and searching of text"4.
  • C#. Normalize() with no argument gives a string "whose binary representation is in Unicode normalization form C"5.
  • Go. "Package norm contains types and functions for normalizing Unicode strings"6. It is in the module golang.org/x/text, so the impl has the table and needs no module.

The impls with the table read the code points. For NFD, each composite becomes its vowel and its mark. For NFC, a mark after a vowel replaces the vowel with the composite.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • nfc-composes and nfd-decomposes: e U+0301 becomes U+00E9 in NFC, and U+00E9 becomes e U+0301 in NFD.
  • already-nfc and already-nfd: a string that is in the form does not change.
  • mixed-nfc and mixed-nfd: one string has both forms of caf U+00E9. The result has one form only.
  • upper-grave, diaeresis, circumflex and umlauts: the other marks, and the upper case vowels.
  • spacing-accent and no-break-space: U+00B4 and U+00A0 have compatibility decompositions only, so NFC and NFD do not change them.
  • sharp-s: U+00DF has no decomposition.
  • empty: the result is empty.

Pitfalls

  • Python == compares code points. The 2 forms of caf U+00E9 are equal only after the same form:
import unicodedata

a = "caf\u00e9"
b = "cafe\u0301"
print(a == b, unicodedata.normalize("NFC", a) == unicodedata.normalize("NFC", b))
Output
False True
  • JavaScript: 2 normalized strings make a string that is not normalized. "none of the Normalization Forms are closed under string concatenation"1. Normalize the result of a concatenation again:
const x = "e";
const y = "\u0301";
console.log(x.normalize() + y.normalize() === (x + y).normalize());
Output
false
  • Java NFKC changes the text. NFC keeps the ligature U+FB01 as 1 character, and NFKC makes it the 2 letters fi. Compatibility equivalents "may have distinct visual appearances or behaviors"1, so do not use NFKC on text that a person reads:
import java.text.Normalizer;

public class Main {
  public static void main(String[] args) {
    String ligature = "\ufb01";
    String nfc = Normalizer.normalize(ligature, Normalizer.Form.NFC);
    String nfkc = Normalizer.normalize(ligature, Normalizer.Form.NFKC);
    System.out.println(nfc.length() + " " + nfkc);
  }
}
Output
1 fi
  • C# Normalize() with no argument gives NFC. IsNormalized() also checks NFC. A string in NFD is not normalized for it:
using System;

string s = "e\u0301";
Console.WriteLine($"{s.IsNormalized()} {s.Normalize().Length}");
Output
False 1
  • Go: a search finds a part of a letter. In NFD, cafe U+0301 contains cafe, but the reader sees U+00E9 at the end, not e. In NFC, the search finds nothing:
package main

import (
	"fmt"
	"strings"
)

func main() {
	decomposed := "cafe\u0301"
	composed := "caf\u00e9"
	fmt.Println(strings.Contains(decomposed, "cafe"), strings.Contains(composed, "cafe"))
}
Output
true false
  • Rust: the 2 forms have different lengths. In NFC the word is 5 bytes, and in NFD it is 6 bytes. A limit on the length gives a different result for the same text:
fn main() {
    let composed = "caf\u{e9}";
    let decomposed = "cafe\u{301}";
    println!("{} {} {}", composed.len(), decomposed.len(), composed == decomposed);
}
Output
5 6 false
  • C: the 2 forms sort at different places. strcmp compares bytes. e U+0301 comes before f, and U+00E9 comes after it:
#include <stdio.h>
#include <string.h>

int main(void) {
    int decomposed = strcmp("e\xcc\x81", "f") < 0;
    int composed = strcmp("\xc3\xa9", "f") < 0;
    printf("%d %d\n", decomposed, composed);
    return 0;
}
Output
1 0
  • C++: a set holds the same word 2 times. Normalize each key before it goes into a std::set or a std::map:
#include <iostream>
#include <set>
#include <string>

int main() {
    std::set<std::string> words = {"caf\xc3\xa9", "cafe\xcc\x81"};
    std::cout << words.size() << "\n";
}
Output
2
  • Bash: quote the right side of ==. With ==, "the string to the right of the operator is considered a pattern"7. If you quote a part of the pattern, "the quoted portion is matched literally"7. With the quotes, the 2 forms are different:
a=$'caf\xc3\xa9'
b=$'cafe\xcc\x81'
if [[ $a == "$b" ]]; then echo same; else echo different; fi
Output
different

Code

The build runs the native tests of each language in a pinned toolchain.

normalize.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/normalize-unicode-text/.
"""Put a string in the normalization form NFC or NFD."""

import unicodedata


def normalize(s: str, form: str) -> str:
    """Return s in the form NFC or NFD. The 2 forms of the same text compare equal only after this."""
    return unicodedata.normalize(form, s)
test_normalize.py 31 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/normalize-unicode-text/.

import pytest

from normalize import normalize

# U+00E9 is NFC, and e U+0301 is NFD. Both are the same text.
CASES = {
    "nfc-composes": ("e\u0301", "NFC", "\u00e9"),
    "nfd-decomposes": ("\u00e9", "NFD", "e\u0301"),
    "ascii": ("abc", "NFC", "abc"),
    "empty": ("", "NFD", ""),
    "already-nfc": ("\u00e9", "NFC", "\u00e9"),
    "already-nfd": ("e\u0301", "NFD", "e\u0301"),
    "mixed-nfc": ("cafe\u0301 caf\u00e9", "NFC", "caf\u00e9 caf\u00e9"),
    "mixed-nfd": ("cafe\u0301 caf\u00e9", "NFD", "cafe\u0301 cafe\u0301"),
    "upper-grave": ("E\u0300", "NFC", "\u00c8"),
    "diaeresis": ("u\u0308ber", "NFC", "\u00fcber"),
    "circumflex": ("\u00ee", "NFD", "i\u0302"),
    "umlauts": ("\u00c4\u00d6\u00dc\u00e4\u00f6\u00fc", "NFD", "A\u0308O\u0308U\u0308a\u0308o\u0308u\u0308"),
    "spacing-accent": ("\u00b4e", "NFC", "\u00b4e"),
    "no-break-space": ("a\u00a0b", "NFD", "a\u00a0b"),
    "sharp-s": ("stra\u00dfe", "NFD", "stra\u00dfe"),
}


@pytest.mark.parametrize("name", CASES)
def test_normalize(name):
    s, form, want = CASES[name]
    assert normalize(s, form) == want
normalize.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.
#include "normalize.hpp"

#include <array>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <utility>
#include <vector>

namespace {

constexpr std::string_view vowels = "AEIOUaeiou";
constexpr std::array<char32_t, 4> marks = {0x300, 0x301, 0x302, 0x308};

// composites[i][j] is the composite of vowels[i] in upper case and marks[j].
constexpr std::array<std::array<char32_t, 4>, 5> composites = {{
    {0xC0, 0xC1, 0xC2, 0xC4},
    {0xC8, 0xC9, 0xCA, 0xCB},
    {0xCC, 0xCD, 0xCE, 0xCF},
    {0xD2, 0xD3, 0xD4, 0xD6},
    {0xD9, 0xDA, 0xDB, 0xDC},
}};

char32_t composite(std::size_t i, std::size_t j) {
    return i >= 5 ? composites[i - 5][j] + 0x20 : composites[i][j];
}

std::optional<char32_t> compose(char32_t v, char32_t m) {
    for (std::size_t i = 0; i < vowels.size(); i++) {
        for (std::size_t j = 0; j < marks.size(); j++) {
            if (static_cast<char32_t>(vowels[i]) == v && marks[j] == m) {
                return composite(i, j);
            }
        }
    }
    return std::nullopt;
}

std::optional<std::pair<char32_t, char32_t>> decompose(char32_t c) {
    for (std::size_t i = 0; i < vowels.size(); i++) {
        for (std::size_t j = 0; j < marks.size(); j++) {
            if (composite(i, j) == c) {
                return std::pair{static_cast<char32_t>(vowels[i]), marks[j]};
            }
        }
    }
    return std::nullopt;
}

std::vector<char32_t> decode(std::string_view s) {
    std::vector<char32_t> out;
    for (std::size_t i = 0; i < s.size();) {
        auto b0 = static_cast<unsigned char>(s[i]);
        std::size_t n = b0 < 0x80 ? 1 : b0 < 0xE0 ? 2 : b0 < 0xF0 ? 3 : 4;
        char32_t c = n == 1 ? b0 : (b0 & (0x7Fu >> n));
        for (std::size_t j = 1; j < n; j++) {
            c = (c << 6) | (static_cast<unsigned char>(s[i + j]) & 0x3Fu);
        }
        out.push_back(c);
        i += n;
    }
    return out;
}

void encode(std::string &out, char32_t c) {
    if (c < 0x80) {
        out += static_cast<char>(c);
    } else {
        out += static_cast<char>(0xC0 | (c >> 6));
        out += static_cast<char>(0x80 | (c & 0x3F));
    }
}

} // namespace

std::string normalize(std::string_view s, std::string_view form) {
    std::vector<char32_t> out;
    for (char32_t c : decode(s)) {
        if (form == "NFD") {
            if (auto d = decompose(c)) {
                out.push_back(d->first);
                out.push_back(d->second);
                continue;
            }
        } else if (!out.empty()) {
            if (auto p = compose(out.back(), c)) {
                out.back() = *p;
                continue;
            }
        }
        out.push_back(c);
    }
    std::string r;
    for (char32_t c : out) {
        encode(r, c);
    }
    return r;
}
normalize.hpp 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.
#ifndef NORMALIZE_HPP
#define NORMALIZE_HPP

#include <string>
#include <string_view>

// normalize returns the UTF-8 string s in the form "NFC" or "NFD", for the
// code points of the contract.
std::string normalize(std::string_view s, std::string_view form);

#endif
test_normalize.cpp 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

#include "normalize.hpp"

#include <iostream>
#include <string>
#include <string_view>

static int failures = 0;

static void check(std::string_view name, std::string_view s, std::string_view form, std::string_view want) {
    std::string got = normalize(s, form);
    if (got != want) {
        std::cerr << "case " << name << ": got " << got << ", want " << want << "\n";
        failures++;
    }
}

// U+00E9 is NFC, and e U+0301 is NFD. Both are the same text.
int main() {
    check("nfc-composes", "e\xcc\x81", "NFC", "\xc3\xa9");
    check("nfd-decomposes", "\xc3\xa9", "NFD", "e\xcc\x81");
    check("ascii", "abc", "NFC", "abc");
    check("empty", "", "NFD", "");
    check("already-nfc", "\xc3\xa9", "NFC", "\xc3\xa9");
    check("already-nfd", "e\xcc\x81", "NFD", "e\xcc\x81");
    check("mixed-nfc", "cafe\xcc\x81 caf\xc3\xa9", "NFC", "caf\xc3\xa9 caf\xc3\xa9");
    check("mixed-nfd", "cafe\xcc\x81 caf\xc3\xa9", "NFD", "cafe\xcc\x81 cafe\xcc\x81");
    check("upper-grave", "E\xcc\x80", "NFC", "\xc3\x88");
    check("diaeresis", "u\xcc\x88" "ber", "NFC", "\xc3\xbc" "ber");
    check("circumflex", "\xc3\xae", "NFD", "i\xcc\x82");
    check("umlauts", "\xc3\x84\xc3\x96\xc3\x9c\xc3\xa4\xc3\xb6\xc3\xbc", "NFD", "A\xcc\x88O\xcc\x88U\xcc\x88" "a\xcc\x88o\xcc\x88u\xcc\x88");
    check("spacing-accent", "\xc2\xb4" "e", "NFC", "\xc2\xb4" "e");
    check("no-break-space", "a\xc2\xa0" "b", "NFD", "a\xc2\xa0" "b");
    check("sharp-s", "stra\xc3\x9f" "e", "NFD", "stra\xc3\x9f" "e");
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Normalization.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

import java.text.Normalizer;

final class Normalization {
  private Normalization() {}

  // normalize returns s in the form NFC or NFD. The 2 forms of the same text
  // are different strings, so equals is true only after this.
  static String normalize(String s, String form) {
    return Normalizer.normalize(s, Normalizer.Form.valueOf(form));
  }
}
NormalizationTest.java 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class NormalizationTest {
  // U+00E9 is NFC, and e U+0301 is NFD. Both are the same text.
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("nfc-composes", "e\u0301", "NFC", "\u00e9"),
        Arguments.of("nfd-decomposes", "\u00e9", "NFD", "e\u0301"),
        Arguments.of("ascii", "abc", "NFC", "abc"),
        Arguments.of("empty", "", "NFD", ""),
        Arguments.of("already-nfc", "\u00e9", "NFC", "\u00e9"),
        Arguments.of("already-nfd", "e\u0301", "NFD", "e\u0301"),
        Arguments.of("mixed-nfc", "cafe\u0301 caf\u00e9", "NFC", "caf\u00e9 caf\u00e9"),
        Arguments.of("mixed-nfd", "cafe\u0301 caf\u00e9", "NFD", "cafe\u0301 cafe\u0301"),
        Arguments.of("upper-grave", "E\u0300", "NFC", "\u00c8"),
        Arguments.of("diaeresis", "u\u0308ber", "NFC", "\u00fcber"),
        Arguments.of("circumflex", "\u00ee", "NFD", "i\u0302"),
        Arguments.of("umlauts", "\u00c4\u00d6\u00dc\u00e4\u00f6\u00fc", "NFD", "A\u0308O\u0308U\u0308a\u0308o\u0308u\u0308"),
        Arguments.of("spacing-accent", "\u00b4e", "NFC", "\u00b4e"),
        Arguments.of("no-break-space", "a\u00a0b", "NFD", "a\u00a0b"),
        Arguments.of("sharp-s", "stra\u00dfe", "NFD", "stra\u00dfe"));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void normalize(String name, String s, String form, String want) {
    assertEquals(want, Normalization.normalize(s, form));
  }
}
normalize.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.
#include "normalize.h"

#include <stdint.h>
#include <stdlib.h>
#include <string.h>

static const char vowels[] = "AEIOUaeiou";
static const uint32_t marks[4] = {0x300, 0x301, 0x302, 0x308};

// composites[i][j] is the composite of vowels[i] in upper case and marks[j].
static const uint32_t composites[5][4] = {
    {0xC0, 0xC1, 0xC2, 0xC4}, {0xC8, 0xC9, 0xCA, 0xCB}, {0xCC, 0xCD, 0xCE, 0xCF},
    {0xD2, 0xD3, 0xD4, 0xD6}, {0xD9, 0xDA, 0xDB, 0xDC},
};

static uint32_t composite(size_t i, size_t j) {
    return i >= 5 ? composites[i - 5][j] + 0x20 : composites[i][j];
}

// decode reads the UTF-8 sequence at *p, and moves *p past it.
static uint32_t decode(const unsigned char **p) {
    const unsigned char *b = *p;
    size_t n = b[0] < 0x80 ? 1 : b[0] < 0xE0 ? 2 : b[0] < 0xF0 ? 3 : 4;
    uint32_t c = n == 1 ? b[0] : (uint32_t)(b[0] & (0x7F >> n));
    for (size_t i = 1; i < n; i++) {
        c = (c << 6) | (uint32_t)(b[i] & 0x3F);
    }
    *p = b + n;
    return c;
}

// encode writes the UTF-8 form of c, which is below U+0800, at out.
static char *encode(char *out, uint32_t c) {
    if (c < 0x80) {
        *out++ = (char)c;
    } else {
        *out++ = (char)(0xC0 | (c >> 6));
        *out++ = (char)(0x80 | (c & 0x3F));
    }
    return out;
}

char *normalize(const char *s, const char *form) {
    int nfd = strcmp(form, "NFD") == 0;
    // NFD makes each 2-byte composite 3 bytes, so the result is at most
    // 1.5 times as long as s.
    char *out = malloc(strlen(s) * 3 / 2 + 1);
    if (out == NULL) {
        return NULL;
    }
    char *end = out;
    uint32_t last = 0;      // the last code point written
    char *last_at = NULL;   // where it starts in out
    const unsigned char *p = (const unsigned char *)s;
    while (*p != 0) {
        uint32_t c = decode(&p);
        int done = 0;
        for (size_t i = 0; i < 10 && !done; i++) {
            for (size_t j = 0; j < 4 && !done; j++) {
                if (nfd && composite(i, j) == c) {
                    end = encode(end, (uint32_t)vowels[i]);
                    end = encode(end, marks[j]);
                    done = 1;
                } else if (!nfd && last_at != NULL && last == (uint32_t)vowels[i] && c == marks[j]) {
                    end = encode(last_at, composite(i, j));
                    last = composite(i, j);
                    done = 1;
                }
            }
        }
        if (!done) {
            last_at = end;
            last = c;
            end = encode(end, c);
        }
    }
    *end = 0;
    return out;
}
normalize.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.
#ifndef NORMALIZE_H
#define NORMALIZE_H

// normalize returns a new UTF-8 string with s in the form "NFC" or "NFD", for
// the code points of the contract. The caller frees it. It returns NULL if
// there is no memory.
char *normalize(const char *s, const char *form);

#endif
test_normalize.c 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

#include "normalize.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int failures = 0;

static void check(const char *name, const char *s, const char *form, const char *want) {
    char *got = normalize(s, form);
    if (got == NULL || strcmp(got, want) != 0) {
        fprintf(stderr, "case %s: got %s, want %s\n", name, got == NULL ? "NULL" : got, want);
        failures++;
    }
    free(got);
}

// U+00E9 is NFC, and e U+0301 is NFD. Both are the same text.
int main(void) {
    check("nfc-composes", "e\xcc\x81", "NFC", "\xc3\xa9");
    check("nfd-decomposes", "\xc3\xa9", "NFD", "e\xcc\x81");
    check("ascii", "abc", "NFC", "abc");
    check("empty", "", "NFD", "");
    check("already-nfc", "\xc3\xa9", "NFC", "\xc3\xa9");
    check("already-nfd", "e\xcc\x81", "NFD", "e\xcc\x81");
    check("mixed-nfc", "cafe\xcc\x81 caf\xc3\xa9", "NFC", "caf\xc3\xa9 caf\xc3\xa9");
    check("mixed-nfd", "cafe\xcc\x81 caf\xc3\xa9", "NFD", "cafe\xcc\x81 cafe\xcc\x81");
    check("upper-grave", "E\xcc\x80", "NFC", "\xc3\x88");
    check("diaeresis", "u\xcc\x88" "ber", "NFC", "\xc3\xbc" "ber");
    check("circumflex", "\xc3\xae", "NFD", "i\xcc\x82");
    check("umlauts", "\xc3\x84\xc3\x96\xc3\x9c\xc3\xa4\xc3\xb6\xc3\xbc", "NFD", "A\xcc\x88O\xcc\x88U\xcc\x88" "a\xcc\x88o\xcc\x88u\xcc\x88");
    check("spacing-accent", "\xc2\xb4" "e", "NFC", "\xc2\xb4" "e");
    check("no-break-space", "a\xc2\xa0" "b", "NFD", "a\xc2\xa0" "b");
    check("sharp-s", "stra\xc3\x9f" "e", "NFD", "stra\xc3\x9f" "e");
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Normalization.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

using System.Text;

public static class Normalization
{
    // Normalize returns s in the form NFC or NFD. The 2 forms of the same text
    // are different strings, so == is true only after this.
    public static string Normalize(string s, string form)
    {
        return s.Normalize(form == "NFD" ? NormalizationForm.FormD : NormalizationForm.FormC);
    }
}
NormalizationTests.cs 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

using Xunit;

public sealed class NormalizationTests
{
    // U+00E9 is NFC, and e U+0301 is NFD. Both are the same text.
    public static TheoryData<string, string, string, string> Cases => new()
    {
        { "nfc-composes", "e\u0301", "NFC", "\u00e9" },
        { "nfd-decomposes", "\u00e9", "NFD", "e\u0301" },
        { "ascii", "abc", "NFC", "abc" },
        { "empty", "", "NFD", "" },
        { "already-nfc", "\u00e9", "NFC", "\u00e9" },
        { "already-nfd", "e\u0301", "NFD", "e\u0301" },
        { "mixed-nfc", "cafe\u0301 caf\u00e9", "NFC", "caf\u00e9 caf\u00e9" },
        { "mixed-nfd", "cafe\u0301 caf\u00e9", "NFD", "cafe\u0301 cafe\u0301" },
        { "upper-grave", "E\u0300", "NFC", "\u00c8" },
        { "diaeresis", "u\u0308ber", "NFC", "\u00fcber" },
        { "circumflex", "\u00ee", "NFD", "i\u0302" },
        { "umlauts", "\u00c4\u00d6\u00dc\u00e4\u00f6\u00fc", "NFD", "A\u0308O\u0308U\u0308a\u0308o\u0308u\u0308" },
        { "spacing-accent", "\u00b4e", "NFC", "\u00b4e" },
        { "no-break-space", "a\u00a0b", "NFD", "a\u00a0b" },
        { "sharp-s", "stra\u00dfe", "NFD", "stra\u00dfe" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Normalize(string name, string s, string form, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Normalization.Normalize(s, form));
    }
}
normalize.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

// normalize returns s in the form NFC or NFD. The 2 forms of the same text are
// different strings, so === is true only after this.
export function normalize(s, form) {
  return s.normalize(form);
}
normalize.test.js 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { normalize } from "./normalize.js";

// U+00E9 is NFC, and e U+0301 is NFD. Both are the same text.
const cases = [
  ["nfc-composes", "e\u0301", "NFC", "\u00e9"],
  ["nfd-decomposes", "\u00e9", "NFD", "e\u0301"],
  ["ascii", "abc", "NFC", "abc"],
  ["empty", "", "NFD", ""],
  ["already-nfc", "\u00e9", "NFC", "\u00e9"],
  ["already-nfd", "e\u0301", "NFD", "e\u0301"],
  ["mixed-nfc", "cafe\u0301 caf\u00e9", "NFC", "caf\u00e9 caf\u00e9"],
  ["mixed-nfd", "cafe\u0301 caf\u00e9", "NFD", "cafe\u0301 cafe\u0301"],
  ["upper-grave", "E\u0300", "NFC", "\u00c8"],
  ["diaeresis", "u\u0308ber", "NFC", "\u00fcber"],
  ["circumflex", "\u00ee", "NFD", "i\u0302"],
  ["umlauts", "\u00c4\u00d6\u00dc\u00e4\u00f6\u00fc", "NFD", "A\u0308O\u0308U\u0308a\u0308o\u0308u\u0308"],
  ["spacing-accent", "\u00b4e", "NFC", "\u00b4e"],
  ["no-break-space", "a\u00a0b", "NFD", "a\u00a0b"],
  ["sharp-s", "stra\u00dfe", "NFD", "stra\u00dfe"],
];

for (const [name, s, form, want] of cases) {
  test(name, () => {
    assert.equal(normalize(s, form), want);
  });
}
normalize.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

// normalize returns s in the form NFC or NFD. The 2 forms of the same text are
// different strings, so === is true only after this.
export function normalize(s: string, form: string): string {
  return s.normalize(form);
}
normalize.test.ts 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { normalize } from "./normalize.ts";

// U+00E9 is NFC, and e U+0301 is NFD. Both are the same text.
const cases: [string, string, string, string][] = [
  ["nfc-composes", "e\u0301", "NFC", "\u00e9"],
  ["nfd-decomposes", "\u00e9", "NFD", "e\u0301"],
  ["ascii", "abc", "NFC", "abc"],
  ["empty", "", "NFD", ""],
  ["already-nfc", "\u00e9", "NFC", "\u00e9"],
  ["already-nfd", "e\u0301", "NFD", "e\u0301"],
  ["mixed-nfc", "cafe\u0301 caf\u00e9", "NFC", "caf\u00e9 caf\u00e9"],
  ["mixed-nfd", "cafe\u0301 caf\u00e9", "NFD", "cafe\u0301 cafe\u0301"],
  ["upper-grave", "E\u0300", "NFC", "\u00c8"],
  ["diaeresis", "u\u0308ber", "NFC", "\u00fcber"],
  ["circumflex", "\u00ee", "NFD", "i\u0302"],
  ["umlauts", "\u00c4\u00d6\u00dc\u00e4\u00f6\u00fc", "NFD", "A\u0308O\u0308U\u0308a\u0308o\u0308u\u0308"],
  ["spacing-accent", "\u00b4e", "NFC", "\u00b4e"],
  ["no-break-space", "a\u00a0b", "NFD", "a\u00a0b"],
  ["sharp-s", "stra\u00dfe", "NFD", "stra\u00dfe"],
];

for (const [name, s, form, want] of cases) {
  test(name, () => {
    assert.equal(normalize(s, form), want);
  });
}
normalize.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

// Package normalize puts a string in the form NFC or NFD, for the code points
// of the contract. The table has the 40 pairs of a vowel and a mark.
package normalize

import "strings"

const vowels = "AEIOUaeiou"

var marks = [4]rune{0x300, 0x301, 0x302, 0x308}

// composites[i][j] is the composite of vowels[i] in upper case and marks[j].
var composites = [5][4]rune{
	{0xC0, 0xC1, 0xC2, 0xC4},
	{0xC8, 0xC9, 0xCA, 0xCB},
	{0xCC, 0xCD, 0xCE, 0xCF},
	{0xD2, 0xD3, 0xD4, 0xD6},
	{0xD9, 0xDA, 0xDB, 0xDC},
}

func composite(i, j int) rune {
	if i >= 5 {
		return composites[i-5][j] + 0x20
	}
	return composites[i][j]
}

// compose returns the composite of v and m, if the table has the pair.
func compose(v, m rune) (rune, bool) {
	i := strings.IndexRune(vowels, v)
	for j, x := range marks {
		if i >= 0 && x == m {
			return composite(i, j), true
		}
	}
	return 0, false
}

// decompose returns the vowel and the mark of c, if c is in the table.
func decompose(c rune) (rune, rune, bool) {
	for i, v := range vowels {
		for j, m := range marks {
			if composite(i, j) == c {
				return v, m, true
			}
		}
	}
	return 0, 0, false
}

// Normalize returns s in the form NFC or NFD. The 2 forms of the same text are
// different strings, so == is true only after this.
func Normalize(s, form string) string {
	var out []rune
	for _, c := range s {
		if form == "NFD" {
			if v, m, ok := decompose(c); ok {
				out = append(out, v, m)
				continue
			}
		} else if n := len(out); n > 0 {
			if p, ok := compose(out[n-1], c); ok {
				out[n-1] = p
				continue
			}
		}
		out = append(out, c)
	}
	return string(out)
}
normalize_test.go 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

package normalize

import "testing"

// U+00E9 is NFC, and e U+0301 is NFD. Both are the same text.
var cases = []struct {
	name, s, form, want string
}{
	{"nfc-composes", "e\u0301", "NFC", "\u00e9"},
	{"nfd-decomposes", "\u00e9", "NFD", "e\u0301"},
	{"ascii", "abc", "NFC", "abc"},
	{"empty", "", "NFD", ""},
	{"already-nfc", "\u00e9", "NFC", "\u00e9"},
	{"already-nfd", "e\u0301", "NFD", "e\u0301"},
	{"mixed-nfc", "cafe\u0301 caf\u00e9", "NFC", "caf\u00e9 caf\u00e9"},
	{"mixed-nfd", "cafe\u0301 caf\u00e9", "NFD", "cafe\u0301 cafe\u0301"},
	{"upper-grave", "E\u0300", "NFC", "\u00c8"},
	{"diaeresis", "u\u0308ber", "NFC", "\u00fcber"},
	{"circumflex", "\u00ee", "NFD", "i\u0302"},
	{"umlauts", "\u00c4\u00d6\u00dc\u00e4\u00f6\u00fc", "NFD", "A\u0308O\u0308U\u0308a\u0308o\u0308u\u0308"},
	{"spacing-accent", "\u00b4e", "NFC", "\u00b4e"},
	{"no-break-space", "a\u00a0b", "NFD", "a\u00a0b"},
	{"sharp-s", "stra\u00dfe", "NFD", "stra\u00dfe"},
}

func TestNormalize(t *testing.T) {
	for _, c := range cases {
		if got := Normalize(c.s, c.form); got != c.want {
			t.Errorf("%s: got %+q, want %+q", c.name, got, c.want)
		}
	}
}
normalize.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

const VOWELS: [char; 10] = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'];
const MARKS: [char; 4] = ['\u{300}', '\u{301}', '\u{302}', '\u{308}'];

/// `COMPOSITES[i][j]` is the composite of `VOWELS[i]` in upper case and `MARKS[j]`.
const COMPOSITES: [[u32; 4]; 5] = [
    [0xC0, 0xC1, 0xC2, 0xC4],
    [0xC8, 0xC9, 0xCA, 0xCB],
    [0xCC, 0xCD, 0xCE, 0xCF],
    [0xD2, 0xD3, 0xD4, 0xD6],
    [0xD9, 0xDA, 0xDB, 0xDC],
];

fn composite(i: usize, j: usize) -> char {
    let c = if i >= 5 { COMPOSITES[i - 5][j] + 0x20 } else { COMPOSITES[i][j] };
    char::from_u32(c).unwrap_or('\u{fffd}')
}

/// Returns the composite of `v` and `m`, if the table has the pair.
fn compose(v: char, m: char) -> Option<char> {
    let i = VOWELS.iter().position(|&x| x == v)?;
    let j = MARKS.iter().position(|&x| x == m)?;
    Some(composite(i, j))
}

/// Returns the vowel and the mark of `c`, if `c` is in the table.
fn decompose(c: char) -> Option<(char, char)> {
    (0..10).find_map(|i| (0..4).find(|&j| composite(i, j) == c).map(|j| (VOWELS[i], MARKS[j])))
}

/// Returns `s` in the form NFC or NFD, for the code points of the contract.
/// The 2 forms of the same text are different strings, so `==` is true only
/// after this.
pub fn normalize(s: &str, form: &str) -> String {
    let mut out: Vec<char> = Vec::new();
    for c in s.chars() {
        if form == "NFD" {
            if let Some((v, m)) = decompose(c) {
                out.push(v);
                out.push(m);
                continue;
            }
        } else if let Some(last) = out.last_mut() {
            if let Some(p) = compose(*last, c) {
                *last = p;
                continue;
            }
        }
        out.push(c);
    }
    out.into_iter().collect()
}
tests/normalize_test.rs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/normalize-unicode-text/.

use algo_normalize_unicode_text::normalize;

// U+00E9 is NFC, and e U+0301 is NFD. Both are the same text.
#[test]
fn cases() {
    let cases: [(&str, &str, &str, &str); 15] = [
        ("nfc-composes", "e\u{301}", "NFC", "\u{e9}"),
        ("nfd-decomposes", "\u{e9}", "NFD", "e\u{301}"),
        ("ascii", "abc", "NFC", "abc"),
        ("empty", "", "NFD", ""),
        ("already-nfc", "\u{e9}", "NFC", "\u{e9}"),
        ("already-nfd", "e\u{301}", "NFD", "e\u{301}"),
        ("mixed-nfc", "cafe\u{301} caf\u{e9}", "NFC", "caf\u{e9} caf\u{e9}"),
        ("mixed-nfd", "cafe\u{301} caf\u{e9}", "NFD", "cafe\u{301} cafe\u{301}"),
        ("upper-grave", "E\u{300}", "NFC", "\u{c8}"),
        ("diaeresis", "u\u{308}ber", "NFC", "\u{fc}ber"),
        ("circumflex", "\u{ee}", "NFD", "i\u{302}"),
        ("umlauts", "\u{c4}\u{d6}\u{dc}\u{e4}\u{f6}\u{fc}", "NFD", "A\u{308}O\u{308}U\u{308}a\u{308}o\u{308}u\u{308}"),
        ("spacing-accent", "\u{b4}e", "NFC", "\u{b4}e"),
        ("no-break-space", "a\u{a0}b", "NFD", "a\u{a0}b"),
        ("sharp-s", "stra\u{df}e", "NFD", "stra\u{df}e"),
    ];
    for (name, s, form, want) in cases {
        assert_eq!(normalize(s, form), want, "{name}");
    }
}
normalize.shI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/normalize-unicode-text/.

# normalize S FORM: prints S in the form NFC or NFD, for the code points of the
# contract. The table has the 40 pairs of a vowel and a mark. Each composite is
# from U+00C0 to U+00FF, so its UTF-8 form is the byte 0xC3 and one more byte.
normalize() {
  (
    LC_ALL=C
    s=$1
    vowels=(A E I O U a e i o u)
    marks=($'\xcc\x80' $'\xcc\x81' $'\xcc\x82' $'\xcc\x88')
    upper=(0xC0 0xC1 0xC2 0xC4 0xC8 0xC9 0xCA 0xCB 0xCC 0xCD 0xCE 0xCF
      0xD2 0xD3 0xD4 0xD6 0xD9 0xDA 0xDB 0xDC)
    for ((i = 0; i < 10; i++)); do
      for ((j = 0; j < 4; j++)); do
        ((cp = upper[(i % 5) * 4 + j] + (i >= 5 ? 0x20 : 0)))
        printf -v comp "\\xc3\\x$(printf '%x' $((cp - 0x40)))"
        pair=${vowels[i]}${marks[j]}
        if [[ $2 == NFD ]]; then
          s=${s//"$comp"/"$pair"}
        else
          s=${s//"$pair"/"$comp"}
        fi
      done
    done
    printf '%s\n' "$s"
  )
}
test_normalize.bats 31 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/normalize-unicode-text/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/normalize.sh"
}

check() { # check S FORM WANT
  run normalize "$1" "$2"
  [ "$status" -eq 0 ]
  [ "$output" = "$3" ]
}

# Each string is UTF-8 bytes. U+00E9 is NFC, and e U+0301 is NFD. Both are the same text.
@test "nfc-composes" { check $'e\xcc\x81' NFC $'\xc3\xa9'; }
@test "nfd-decomposes" { check $'\xc3\xa9' NFD $'e\xcc\x81'; }
@test "ascii" { check 'abc' NFC 'abc'; }
@test "empty" { check '' NFD ''; }
@test "already-nfc" { check $'\xc3\xa9' NFC $'\xc3\xa9'; }
@test "already-nfd" { check $'e\xcc\x81' NFD $'e\xcc\x81'; }
@test "mixed-nfc" { check $'cafe\xcc\x81 caf\xc3\xa9' NFC $'caf\xc3\xa9 caf\xc3\xa9'; }
@test "mixed-nfd" { check $'cafe\xcc\x81 caf\xc3\xa9' NFD $'cafe\xcc\x81 cafe\xcc\x81'; }
@test "upper-grave" { check $'E\xcc\x80' NFC $'\xc3\x88'; }
@test "diaeresis" { check $'u\xcc\x88ber' NFC $'\xc3\xbcber'; }
@test "circumflex" { check $'\xc3\xae' NFD $'i\xcc\x82'; }
@test "umlauts" { check $'\xc3\x84\xc3\x96\xc3\x9c\xc3\xa4\xc3\xb6\xc3\xbc' NFD $'A\xcc\x88O\xcc\x88U\xcc\x88a\xcc\x88o\xcc\x88u\xcc\x88'; }
@test "spacing-accent" { check $'\xc2\xb4e' NFC $'\xc2\xb4e'; }
@test "no-break-space" { check $'a\xc2\xa0b' NFD $'a\xc2\xa0b'; }
@test "sharp-s" { check $'stra\xc3\x9fe' NFD $'stra\xc3\x9fe'; }

References

  1. Unicode Standard Annex, 1.1 Canonical and Compatibility Equivalence; 1.2 Normalization Forms; 1.4 Concatenation of Normalized Strings
  2. The Python Standard Library, unicodedata, normalize
  3. MDN Web Docs, String.prototype.normalize(), Parameters
  4. Java SE 25 API, Class Normalizer, Class description
  5. .NET API reference, String.Normalize, Normalize()
  6. Go module golang.org/x/text, package norm, Overview
  7. Bash Reference Manual, 3.2.5.2 Conditional Constructs

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source