Conceptcore
Characters, code points and graphemes
Also called character, code point, code unit, grapheme cluster, Unicode, UTF-16, surrogate pair, rune, Unicode normalization, NFC, text encoding.
Text has four layers. Readers see grapheme clusters, Unicode numbers code points, an encoding stores them as code units, and the units become bytes. Each language counts one layer.
- Applies to
- core-languages
Idea
Text in a program has four layers. A reader sees characters, which Unicode calls grapheme clusters. Unicode gives each abstract character a number, its code point, and one visible character can take several code points, such as a letter and a combining accent, or an emoji and a skin tone modifier. An encoding form stores each code point as one or more code units of 8, 16 or 32 bits, and a byte order stores the code units as bytes. "The length of a string" can mean any of these four counts, and each language picks one. Most bugs with text come from code that uses one layer where it means another.
import unicodedata
SKIN = range(0x1F3FB, 0x1F400) # skin tone modifiers
FLAG = range(0x1F1E6, 0x1F200) # regional indicator letters
def graphemes(s): # a simplified version of the rules of UAX #29
out = []
for ch in s:
cp, prev = ord(ch), out[-1] if out else ""
joins = (
unicodedata.combining(ch) # a combining accent
or ch in "\u200d\ufe0f" # zero width joiner, emoji style
or prev.endswith("\u200d") # the character after a joiner
or cp in SKIN
or (cp in FLAG and len(prev) == 1 and ord(prev) in FLAG)
)
if out and joins:
out[-1] += ch
else:
out.append(ch)
return out
samples = ["A", "\u00e9", "e\u0301", "\u20ac", "\U0001f600",
"\U0001f44d\U0001f3fd", "\U0001f1fb\U0001f1f3",
"\U0001f469\u200d\U0001f4bb"]
print("graphemes code-points utf16-units utf8-bytes first code point")
for s in samples:
units = len(s.encode("utf-16-le")) // 2
first = f"U+{ord(s[0]):04X} {unicodedata.name(s[0])}"
print(f"{len(graphemes(s)):9} {len(s):11} {units:11} {len(s.encode()):10} {first}")
graphemes code-points utf16-units utf8-bytes first code point
1 1 1 1 U+0041 LATIN CAPITAL LETTER A
1 1 1 2 U+00E9 LATIN SMALL LETTER E WITH ACUTE
1 2 2 3 U+0065 LATIN SMALL LETTER E
1 1 1 3 U+20AC EURO SIGN
1 1 2 4 U+1F600 GRINNING FACE
1 2 4 8 U+1F44D THUMBS UP SIGN
1 2 4 8 U+1F1FB REGIONAL INDICATOR SYMBOL LETTER V
1 3 5 11 U+1F469 WOMAN
The simplified graphemes function follows a few of the rules of Unicode text segmentation: a combining mark, a skin tone modifier, a zero width joiner and the character after it, and the second letter of a flag all join the character before them. Each sample is one character on the screen. The decomposed e with an acute accent is 2 code points, the grinning face is 1 code point but 2 UTF-16 units, and the woman at a laptop is 3 code points joined into one picture, 5 UTF-16 units and 11 bytes of UTF-8. No count other than the first matches what a reader calls the length.
How it works
Characters and grapheme clusters. The unit that a reader sees, selects with the cursor and deletes with one key press is not a fixed number of anything in memory. Unicode Standard Annex #29 says: "A single Unicode code point is often, but not always the same as a basic unit of a writing system for a language, or what a typical user might think of as a “character”."1 It defines grapheme clusters as "user-perceived characters" and gives rules to find their boundaries in a string of code points.1 The rules cover combining marks, Hangul syllables, emoji sequences with joiners and modifiers, and pairs of regional indicators that make a flag. The rules change as Unicode adds characters, so code that splits, truncates or reverses text for display uses a library that tracks the current version of the rules.
Code points. Unicode assigns a number to each abstract character, from 0 to 0x10FFFF, and writes it as U+ followed by at least four hexadecimal digits: U+0041 is A and U+1F44D is the thumbs up sign. The Python documentation describes the model: "a Unicode string is a sequence of code points, which are numbers from 0 through 0x10FFFF (1,114,111 decimal)."2 The range from U+D800 to U+DFFF is reserved for the surrogates of UTF-16 and holds no characters. A code point outside that range is a Unicode scalar value, and Rust's char type holds exactly these: "A char is a ‘Unicode scalar value’, which is any ‘Unicode code point’ other than a surrogate code point."3
Code units and encoding forms. An encoding form maps each code point to a sequence of code units. The Python documentation continues: "This sequence of code points needs to be represented in memory as a set of code units, and code units are then mapped to 8-bit bytes."2 UTF-8 uses 1 to 4 bytes for each code point, keeps ASCII as it is, and is the usual form for files, network protocols and the web; see UTF-8. UTF-16 uses one 16-bit unit for code points up to U+FFFF and a surrogate pair of two units for the rest. UTF-32 uses one 32-bit unit for each code point, which makes indexing by code point simple and costs 4 bytes for each character. When UTF-16 or UTF-32 goes into bytes, the order of the bytes in each unit matters, and a byte order mark or a label such as UTF-16LE states it.
Strings in languages. The string type of a language fixes which layer its indices and lengths count. Java, JavaScript and C# chose 16-bit units. The Java documentation says: "A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs" and "Index values refer to char code units, so a supplementary character uses two positions in a String."4 MDN says the same of JavaScript: "Strings are represented fundamentally as sequences of UTF-16 code units."5 Go and Rust store UTF-8 bytes. The Go blog says: "In Go, a string is in effect a read-only slice of bytes."6 It adds that a string literal holds valid UTF-8, and that "Those sequences represent Unicode code points, called runes."6 Python hides the encoding and indexes by code point. No mainstream string type indexes by grapheme cluster, because finding one needs a scan with the segmentation rules.
Normalization. Some characters have more than one sequence of code points. é is U+00E9, or e followed by U+0301 COMBINING ACUTE ACCENT. Unicode Standard Annex #15 calls such sequences canonically equivalent: "Canonical equivalence is a fundamental equivalency between characters or sequences of characters which represent the same abstract character, and which when correctly displayed should always have the same visual appearance and behavior."7 A program that compares code points sees two different strings. Normalization converts text to one form: NFC composes characters where it can, and NFD decomposes them. NFKC and NFKD also fold compatibility characters, such as the ligature fi to fi, and are for search and identifiers, not for storage of the text that a user wrote.
Case and comparison. Case mapping is not one character to one character. The German ß has the upper case SS, so upper can make a string longer, and the Turkish dotless ı makes the result depend on the language of the text. Comparing text without case uses case folding, not lower case. Sorting text for people uses collation rules for a language, not the order of code points, and is a job for a library such as ICU.
Invalid input. Bytes from outside a program may not be valid in the encoding that the program expects. A decoder can reject the input, or replace each bad sequence with U+FFFD REPLACEMENT CHARACTER, as from_utf8_lossy in Rust and errors="replace" in Python do. Strings of 16-bit units have their own invalid case. MDN defines a lone surrogate as a 16-bit code unit in the range of high surrogates that has no low surrogate after it, or the reverse, and such a string cannot convert to UTF-8 without loss.5 Code that cuts a string at a fixed index of units or bytes can make invalid text from valid text, as the wrong blocks of the JavaScript and Go files show.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | As JavaScript; strings are sequences of UTF-16 code units. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | On the JVM, a String holds UTF-16 code units, as in Java; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Native | A column has a character set and a collation, and LENGTH counts characters while OCTET_LENGTH counts bytes. |
| Bash | Idiom | The length of a variable counts characters in the current locale, and tools such as iconv convert encodings. |
| PowerShell | Native | Strings are .NET strings of UTF-16 code units, with the same Rune and StringInfo types as C#; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Native | The charset declaration tells the browser the encoding, and character references such as 👍 name code points. |
| CSS | Native | The @charset rule and escapes such as \1F44D name code points in style sheets. |
| Regular expressions | Native | Engines match code points or code units, and many support \X for one grapheme cluster and \p{...} for Unicode properties. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | str of code points; encode, unicodedata |
| JavaScript | native | UTF-16 units; code point iteration; Intl.Segmenter |
| TypeScript | native | as JavaScript |
| Java | native | UTF-16 String; code point methods; \X in regex |
| Kotlin | native | UTF-16 String on the JVM |
| C# | native | UTF-16 string; Rune; StringInfo |
| Go | native | UTF-8 bytes; rune; unicode/utf8 |
| Rust | native | UTF-8 str; char is a scalar value |
| C | idiom | char is a byte; UTF-8 by hand or a library |
| C++ | native | char8_t, char16_t, char32_t strings |
| Bash | idiom | lengths in the current locale; iconv |
| PowerShell | native | .NET strings of UTF-16 units |
| SQL | native | character sets, collations, CHAR_LENGTH |
| Regex | native | \X and \p{...} in many engines |
| HTML | native | the charset declaration; character references |
| CSS | native | @charset; escapes such as \1F44D |
Every example file uses the same string, café with a decomposed accent, a space and a thumbs up with a skin tone. A reader sees 6 characters. The string has 8 code points, 10 UTF-16 units and 15 bytes of UTF-8, and each language reports the count of its own layer: Python 8, JavaScript, Java and C# 10, Go and Rust 15. Java with \X, C# with StringInfo and JavaScript with Intl.Segmenter also count the 6 grapheme clusters. Python, Go and Rust need a package outside the standard library for that count.
Languages differ in what a string can hold. A Rust str is always valid UTF-8, and the standard library checks this when it makes one from bytes. A Go string can hold any bytes, and code checks them with utf8.ValidString when it matters. Strings in Java, JavaScript and C# can hold lone surrogates. A Python str can hold any code point, including surrogates, which some decoders use to carry undecodable bytes through a program.
import unicodedata
s = "cafe\u0301 \U0001f44d\U0001f3fd" # e + combining acute, thumbs up + skin tone
print(len(s), len(s.encode("utf-8")), len(s.encode("utf-16-le")) // 2)
print([f"U+{ord(c):04X}" for c in s[3:5]])
nfc = unicodedata.normalize("NFC", s) # compose e + accent into one code point
print(len(nfc), unicodedata.name(nfc[3]))
print("Stra\u00dfe".upper(), "Stra\u00dfe".casefold() == "STRASSE".casefold())
print(bytes([0x63, 0x61, 0x66, 0xC3, 0xA9]).decode("utf-8"))
print(b"caf\xe9".decode("utf-8", errors="replace") == "caf\ufffd")
8 15 10
['U+0065', 'U+0301']
7 LATIN SMALL LETTER E WITH ACUTE
STRASSE True
café
True
This code runs but gives a wrong answer on purpose.
typed = "caf\u00e9" # one code point for the accented letter
pasted = "cafe\u0301" # e followed by a combining accent
print(typed == pasted, len(typed), len(pasted))
print({typed: 1}.get(pasted))
False 4 5
None
- Verdict: native. A Python
stris a sequence of code points, solencounts code points: 8 for the sample, which a reader sees as 6 characters.encodegives the bytes of an encoding, 15 in UTF-8 and 10 UTF-16 code units.unicodedata.normalizeconverts between the composed and decomposed forms, andcasefoldgives a form for comparing text without case, in whichßmatchesSS. The standard library has no function for grapheme clusters; the third-partyregexmodule supports\X. - Decoding bytes that are not valid UTF-8 raises an error by default;
errors="replace"puts U+FFFD in place of each bad sequence. - The wrong block compares a word typed as one code point with the same word pasted with a combining accent. They look the same but are different strings, so
==and dictionary lookups fail. Normalize text to NFC when it enters the program.
#include <iostream>
#include <string>
int main() {
std::u8string s8 = u8"cafe\u0301 \U0001F44D\U0001F3FD"; // UTF-8 code units
std::u16string s16 = u"cafe\u0301 \U0001F44D\U0001F3FD"; // UTF-16 code units
std::u32string s32 = U"cafe\u0301 \U0001F44D\U0001F3FD"; // one unit per code point
std::cout << s8.size() << ' ' << s16.size() << ' ' << s32.size() << '\n';
std::cout << std::hex << std::uppercase << static_cast<unsigned>(s16[6]) << ' '
<< static_cast<unsigned>(s32[6]) << std::dec << '\n';
std::string bytes = "caf\xC3\xA9"; // std::string holds bytes, whatever they encode
std::cout << bytes.size() << ' ' << sizeof(char8_t) << ' ' << sizeof(char16_t) << ' '
<< sizeof(char32_t) << '\n';
}
15 10 8
D83D 1F44D
5 1 2 4
- Verdict: native. C++ has string types for each Unicode encoding form:
std::u8stringofchar8_tfor UTF-8,std::u16stringfor UTF-16 andstd::u32stringfor UTF-32, and the literal prefixesu8,uandUencode a literal in each form. The sample takes 15, 10 and 8 units in the three forms.std::stringholds bytes in any encoding. - The standard library has no normalization, segmentation or case mapping for Unicode. Programs use ICU or a similar library for them.
import java.nio.charset.StandardCharsets;
import java.text.Normalizer;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String s = "cafe\u0301 \uD83D\uDC4D\uD83C\uDFFD"; // the emoji as surrogate pairs
long graphemes = Pattern.compile("\\X").matcher(s).results().count();
System.out.println(s.length() + " " + s.codePointCount(0, s.length()) + " "
+ graphemes + " " + s.getBytes(StandardCharsets.UTF_8).length);
System.out.println(Integer.toHexString(s.charAt(6)) + " " + Integer.toHexString(s.codePointAt(6))
+ " " + Character.isSurrogate(s.charAt(6)));
String nfc = Normalizer.normalize(s, Normalizer.Form.NFC);
System.out.println(nfc.length() + " " + nfc.equals("caf\u00e9 \uD83D\uDC4D\uD83C\uDFFD"));
System.out.println("Stra\u00dfe".toUpperCase(java.util.Locale.ROOT));
}
}
10 8 6 15
d83d 1f44d true
9 true
STRASSE
- Verdict: native. A Java
Stringholds UTF-16 code units, andcharis one unit, not one character.lengthcounts units,codePointCountcounts code points, and the regular expression\Xmatches one extended grapheme cluster, so counting its matches gives 6. Methods such ascodePointAtandCharacter.isSurrogatedeal with the pairs that encode characters outside the Basic Multilingual Plane. java.text.Normalizerconverts between normalization forms. Case conversion depends on the locale, so passLocale.ROOTfor text that is not shown to a user.
#include <stdio.h>
#include <string.h>
/* Count code points: every byte that is not a continuation byte (10xxxxxx) starts one. */
static size_t count_code_points(const char *s) {
size_t n = 0;
for (; *s; s++)
if (((unsigned char)*s & 0xC0) != 0x80) n++;
return n;
}
/* Decode the code point that starts at s and store its length in *len. */
static unsigned decode(const unsigned char *s, int *len) {
if (s[0] < 0x80) { *len = 1; return s[0]; }
if (s[0] < 0xE0) { *len = 2; return (s[0] & 0x1Fu) << 6 | (s[1] & 0x3Fu); }
if (s[0] < 0xF0) { *len = 3; return (s[0] & 0x0Fu) << 12 | (s[1] & 0x3Fu) << 6 | (s[2] & 0x3Fu); }
*len = 4;
return (s[0] & 0x07u) << 18 | (s[1] & 0x3Fu) << 12 | (s[2] & 0x3Fu) << 6 | (s[3] & 0x3Fu);
}
int main(void) {
const char *s = "cafe\xCC\x81 \xF0\x9F\x91\x8D\xF0\x9F\x8F\xBD"; /* UTF-8 bytes */
printf("%zu %zu\n", strlen(s), count_code_points(s));
const char *sep = "";
for (const unsigned char *p = (const unsigned char *)s; *p;) {
int len;
unsigned cp = decode(p, &len);
if (cp > 127) {
printf("%sU+%04X/%d", sep, cp, len);
sep = " ";
}
p += len;
}
printf("\n%d\n", (int)sizeof(char));
return 0;
}
15 8
U+0301/2 U+1F44D/4 U+1F3FD/4
1
- Verdict: idiom. In C,
charis one byte and a string is an array of bytes ending in a zero byte, sostrlencounts bytes. The standard library has wide characters and multibyte conversions that depend on the locale, but no portable UTF-8 functions. Programs decode UTF-8 by hand, as the example does, or use a library such as ICU or utf8proc. - Every byte of a UTF-8 sequence after the first has the form
10xxxxxx, so counting the other bytes counts code points. The example trusts its input; a real decoder must reject truncated sequences, overlong forms and surrogates.
using System;
using System.Globalization;
using System.Linq;
using System.Text;
string s = "cafe\u0301 \U0001F44D\U0001F3FD";
Console.WriteLine($"{s.Length} {s.EnumerateRunes().Count()} {new StringInfo(s).LengthInTextElements} {Encoding.UTF8.GetByteCount(s)}");
Console.WriteLine($"{(int)s[6]:X} {Rune.GetRuneAt(s, 6).Value:X} {char.IsSurrogate(s[6])}");
string nfc = s.Normalize(NormalizationForm.FormC);
Console.WriteLine($"{nfc.Length} {nfc == "caf\u00e9 \U0001F44D\U0001F3FD"}");
10 8 6 15
D83D 1F44D True
9 True
- Verdict: native. A .NET
stringholds UTF-16 code units, andLengthcounts them.EnumerateRunesgives code points asRunevalues,StringInfocounts text elements, which are extended grapheme clusters, andEncoding.UTF8converts to bytes.Normalizeconverts between normalization forms.
const s = "cafe\u0301 \u{1F44D}\u{1F3FD}";
console.log(s.length, [...s].length, new TextEncoder().encode(s).length);
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
console.log([...seg.segment(s)].length);
console.log(s.normalize("NFC").length, s.normalize("NFC") === "caf\u00e9 \u{1F44D}\u{1F3FD}");
console.log(s.codePointAt(6).toString(16), s.charCodeAt(6).toString(16), s.charCodeAt(7).toString(16));
10 8 15
6
9 true
1f44d d83d dc4d
This code runs but gives a wrong answer on purpose.
const s = "\u{1F44D}\u{1F3FD} done";
const cut = s.slice(0, 3); // three UTF-16 units: one emoji and half of the next
console.log(cut.length, cut.isWellFormed());
console.log(encodeURIComponent(s.slice(0, 2)));
try {
encodeURIComponent(cut);
} catch (e) {
console.log(e.name);
}
3 false
%F0%9F%91%8D
URIError
- Verdict: native. A JavaScript string is a sequence of UTF-16 code units, so
lengthcounts units: 10 for the sample, where each emoji takes two. Spreading a string with...iterates over code points, andIntl.Segmenterwithgranularity: "grapheme"gives the characters a reader sees.codePointAtreads a whole code point, whilecharCodeAtreads one unit, here the high surrogated83d. - The wrong block cuts a string after three units, which splits the second emoji between its two surrogates. The result is not well-formed, and
encodeURIComponentthrowsURIErrorfor it. Cut strings at grapheme boundaries fromIntl.Segmenter, or at least at code point boundaries.
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
s := "cafe\u0301 \U0001F44D\U0001F3FD"
fmt.Println(len(s), utf8.RuneCountInString(s))
var found []string
for i, r := range s { // range decodes UTF-8 into runes
if r > 127 {
found = append(found, fmt.Sprintf("%d:%U", i, r))
}
}
fmt.Println(strings.Join(found, " "))
b := []byte(s)
fmt.Println(b[4], b[5], utf8.RuneLen('\u0301'))
bad := "caf\xe9" // a Latin-1 byte, not valid UTF-8
r, size := utf8.DecodeRuneInString(bad[3:])
fmt.Println(utf8.ValidString(bad), r == utf8.RuneError, size)
}
15 8
4:U+0301 7:U+1F44D 11:U+1F3FD
204 129 2
false true 1
This code runs but gives a wrong answer on purpose.
package main
import (
"fmt"
"unicode/utf8"
)
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] // cuts at a byte, not at a character
}
func main() {
name := "Ng\u00f4 B\u1ea3o"
short := truncate(name, 3)
fmt.Println(len(short), utf8.ValidString(short))
fmt.Printf("%q\n", short)
}
3 false
"Ng\xc3"
- Verdict: native. A Go string holds bytes, which are UTF-8 by convention, so
lencounts bytes: 15 for the sample. Aruneis a code point,rangeover a string decodes one rune at a time and gives its byte offset, andunicode/utf8counts, checks and decodes runes. An invalid byte decodes toutf8.RuneError, U+FFFD, with a size of 1. Grapheme clusters need a package outside the standard library. - The wrong block truncates a Vietnamese name to 3 bytes. The third byte is the first half of the two bytes of
ô, so the result is not valid UTF-8 and prints as a broken character. Truncate at a rune boundary, withutf8.RuneStartor by counting runes.
fn main() {
let s = "cafe\u{301} \u{1F44D}\u{1F3FD}";
println!("{} {}", s.len(), s.chars().count());
println!("{} {}", s.is_char_boundary(4), s.is_char_boundary(5));
let found: Vec<String> = s
.char_indices()
.filter(|(_, c)| !c.is_ascii())
.map(|(i, c)| format!("{i}:U+{:04X}", c as u32))
.collect();
println!("{}", found.join(" "));
let units: Vec<u16> = s.encode_utf16().collect();
println!("{} {:X}", units.len(), units[6]);
let bytes = vec![0x63, 0x61, 0x66, 0xE9];
println!("{}", String::from_utf8(bytes.clone()).is_err());
println!("{}", String::from_utf8_lossy(&bytes));
println!("{}", "stra\u{df}e".to_uppercase());
}
15 8
true false
4:U+0301 7:U+1F44D 11:U+1F3FD
10 D83D
true
caf�
STRASSE
This code panics, on purpose.
fn main() {
let name = "Ng\u{f4} B\u{1ea3}o";
let short = &name[..3]; // byte 3 is inside the two bytes of the second letter
println!("{short}");
}
- Verdict: native. A Rust
stris always valid UTF-8, andlencounts bytes.charis a Unicode scalar value,charsdecodes the string onecharat a time, andis_char_boundarytells whether a byte index starts a character.encode_utf16gives UTF-16 units for APIs that need them.String::from_utf8rejects invalid bytes, andfrom_utf8_lossyreplaces them with U+FFFD. - The fails block slices a string at byte 3, which falls inside a two-byte character, and the program panics. Slice at indices from
char_indices, or checkis_char_boundaryfirst.
Variations and related ideas
- Legacy encodings. ASCII, the ISO 8859 family, Windows code pages, Shift JIS and GB 18030 encode a smaller set of characters, or the same set in a different way. Programs that read old files must know which one they use, because the bytes do not say.
- Fixed-width strings. UTF-32 strings,
std::u32stringand Python's internal representation give constant-time indexing by code point, but code points are still not characters. - Ropes and indexed text. Text editors store long text in trees of chunks and keep counts of bytes, code points, UTF-16 units and lines for each chunk, so that they can convert positions between the layers quickly.
- Byte strings. Python
bytes, RustVec<u8>andOsString, and Go[]bytehold data that is not text, or text in an unknown encoding, such as file names on Unix. - Binary-to-text encodings. Base64 and percent encoding put bytes into ASCII text. See Base64.
- String operations. Reversing and splitting a string must respect grapheme clusters and code points. See reverse a string and split a string.
Pitfalls
- Length that is not the length.
len,lengthandLengthcount code points, UTF-16 units or bytes. A limit of 10 characters in a form can reject 6 characters that a user typed, or a database column of 10 bytes can reject 4 letters. State which unit each limit uses. - Cutting inside a character. Truncating by bytes or units can split a code point, and truncating by code points can split a grapheme cluster, which drops an accent or breaks an emoji. The wrong blocks in the JavaScript and Go files and the fails block in the Rust file show this. Cut at boundaries from a segmenter.
- Comparing text that is not normalized. Two strings that look the same can differ in their code points, so equality, hashing and lookups fail. The wrong block in the Python file shows this. Normalize text to NFC when it enters the program.
- Guessing the encoding. Reading a file with the default encoding of the machine gives different results on different machines. State the encoding at every boundary, and use UTF-8 where the choice is free.
- Case mapping by hand. Adding 32 to a letter, or upper-casing one character at a time, breaks for every script but basic Latin. Use the case functions of the language with a fixed locale, and casefold to compare.
- Lookalike characters. The Latin
aand the Cyrillicаlook the same and are different code points. Attackers use this in domain names and user names. Check identifiers for mixed scripts, and see code injection.
Cost
Length in code units or bytes is O(1) in most languages, because the string stores it. Counting code points in UTF-8 or UTF-16 takes O(n) time, and counting grapheme clusters takes O(n) time with a table lookup for each code point. Indexing by code point is O(1) in UTF-32 and in Python, which picks 1, 2 or 4 bytes for each code point from the largest one in the string, and O(n) in UTF-8 and UTF-16. Converting between encodings takes O(n) time and a new buffer. UTF-8 takes 1 byte for each ASCII character and up to 3 bytes for other characters of the Basic Multilingual Plane, so it is smaller than UTF-16 for most markup and source code, and larger for text in Chinese or Japanese. Normalization takes O(n) time, and most implementations first check quickly whether the text is already normal, which it usually is.
History
ASCII, published in 1963 by the American Standards Association, gave 128 codes for English letters, digits and controls in 7 bits. ISO 8859 and many national and vendor code pages in the 1980s used the eighth bit for other European letters, and Asian standards used several bytes for each character. Joe Becker of Xerox, with Lee Collins and Mark Davis of Apple, proposed a single 16-bit character set in 1988, and the Unicode Consortium published Unicode 1.0 in 1991. Ken Thompson and Rob Pike designed UTF-8 in 1992 for the Plan 9 operating system.
Sixteen bits proved too few. Unicode 2.0 added surrogate pairs in 1996, which made UTF-16 a variable-width encoding, after Windows NT, Java and JavaScript had already chosen 16-bit characters. This is why length counts code units in those languages, and Java added methods for code points in 2004. Python 3.0 made str a Unicode string in 2008, and Python 3.3 made every build index it by code point in 2012. Go, from 2009, and Rust, from 2015, made UTF-8 the string representation. Emoji came into Unicode in 2010, and their sequences of modifiers and joiners made grapheme clusters a daily problem for programs that had treated a code point as a character.
References
- Unicode Standard Annex #29, Unicode Text Segmentation, 3 Grapheme Cluster Boundaries
- Unicode HOWTO, Python documentation, Definitions
- Primitive Type char, The Rust Standard Library, Validity and Layout
- Class String, Java SE 25 API documentation, Class description
- String, MDN Web Docs, UTF-16 characters, Unicode code points, and grapheme clusters
- Strings, bytes, runes and characters in Go, The Go Blog, What is a string? and Code points, characters, and runes
- Unicode Standard Annex #15, Unicode Normalization Forms, 1.1 Canonical and Compatibility Equivalence
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag V5YGS3 Edit this page History Report an error Markdown