Unicode and encoding
Unicode gives every character a number, a code point, and UTF-8 is the encoding that writes those numbers as bytes. A string in Elixir is always UTF-8, and the binaries lesson showed how to read the bytes; this page is about the text itself: the two spellings of one letter, the cluster a reader calls a character, and the sort that puts Zebra before apple.
The bytes of a text
The three views of one word are its bytes, its code points and its characters. The word café is five bytes, four code points and four characters, and each call names the view it uses:
bytes.exs
word = "café" IO.inspect(byte_size(word)) IO.inspect(:binary.bin_to_list(word)) IO.inspect(String.codepoints(word))
elixir bytes.exs
5
[99, 97, 102, 195, 169]
["c", "a", "f", "é"]
The accented letter is two bytes, 195 and 169, and one code point. The list of bytes is what a file or a socket carries; the list of code points is what a text function iterates. A program that counts bytes to measure a text is wrong for every character outside ASCII, which is the mistake the strings lesson warned about.
Two spellings of one letter
Unicode allows the same letter to be encoded as one code point or as a base letter plus a combining accent. The two values are different binaries and are not equal, and String.normalize/2 is the call that brings them to one form:
normalize.exs
composed = "é" decomposed = "e\u0301" IO.inspect(composed == decomposed) IO.inspect(String.normalize(composed, :nfd) == decomposed) IO.inspect(String.normalize(decomposed, :nfc) == composed)
elixir normalize.exs
false
true
true
:nfc is the composed form and :nfd the decomposed one, and a program that compares text from two sources normalizes both sides first. The classic bug is a lookup that misses: the name typed on one keyboard is decomposed, the name in the list is composed, and typed in names answers false although the reader sees the same word. Normalize before comparing, at the boundary where the text enters the program.
Graphemes and code points
A grapheme is what a reader calls one character, and one grapheme may be several code points. The decomposed é is two code points and one grapheme, which is why String.length/1 answers 1 for it and String.codepoints/1 answers two items:
graphemes.exs
text = String.normalize("é", :nfd) IO.inspect(String.codepoints(text)) IO.inspect(String.graphemes(text)) IO.inspect(String.length(text)) IO.inspect(byte_size(text))
elixir graphemes.exs
["e", "́"]
["é"]
1
3
String.graphemes/1 is the split for anything a reader counts: String.slice/3, the cursor of a text field and the truncation of a title all work in graphemes. A split on code points cuts the accent off its letter, which is the bug that shows as a stray mark at the end of a shortened name.
The sort that surprises
A sort of strings compares code points, and the code points put every capital before every lowercase letter and every accented letter after the ASCII range. The default sort is therefore not the alphabetical order a reader expects:
sort.exs
IO.inspect(Enum.sort(["Zebra", "apple"])) IO.inspect(Enum.sort_by(["Zebra", "apple"], &String.downcase/1)) IO.inspect(Enum.sort(["zebra", "éclair"]))
elixir sort.exs
["Zebra", "apple"]
["apple", "Zebra"]
["zebra", "éclair"]
The second line cases both sides before comparing, which is the fix for the capitals; the third shows that é sorts after z because its code point is higher. A user-facing list sorts by a normalized, lower-cased key, and a collation that follows the rules of a language is a library, not a call of Enum.sort/1.
valid? and printable?
Not every binary is UTF-8. A value that arrives from a file or a socket is checked before a text function reads it, and String.valid?/1 is the check:
valid.exs
IO.inspect(String.valid?("café")) IO.inspect(String.valid?(<<0xFF>>)) IO.inspect(String.printable?("\n"))
elixir valid.exs
true
false
true
String.printable?/1 asks a different question: the value is valid text, and every character in it can be printed or is whitespace. A newline is printable by that rule and a null byte is not, which is the check a program makes before it writes text into a terminal.
The mistake: a binary that is not UTF-8
A function that must know the characters decodes the bytes, and a byte that starts no valid sequence stops it with a UnicodeConversionError. The check on the line before is what a program does instead of crashing:
mistake.exs
binary = <<0xFF>> IO.puts(String.valid?(binary)) IO.inspect(String.to_charlist(binary))
elixir mistake.exs
false
** (UnicodeConversionError) invalid encoding starting at <<255>>
(elixir 1.19.7) lib/string.ex:2935: String.to_charlist/1
mistake.exs:4: (file)
The message names the bytes it could not read, which is what a program needs to report a broken file. String.valid?/1 before the decode turns the crash into a decision, and a binary that is not text at all is kept as the bytes it is: a hash, a key or an image has no characters to decode.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How many bytes does the accented
étake in UTF-8?Answer
two
é is the code point 233 and its UTF-8 encoding is the two bytes 195 and 169.
-
What does
:nfcask ofString.normalize/2?Answer
the composed form of the text
NFC composes a base letter and its accent into one code point; NFD decomposes them.
-
What is a grapheme?
Answer
what a reader sees as one character
One grapheme may be several code points, as a letter with a combining accent is.
-
Why does
Enum.sort(["Zebra", "apple"])put Zebra first?Answer
because it compares code points, and Z is below a
The default sort compares the values by term order, where every capital is below every lowercase letter.
-
What does this program print?
IO.inspect(byte_size("café"))Answer
5
The four characters take five bytes, because é takes two.
-
What does this program print?
IO.inspect(String.valid?(<<0xFF>>))Answer
false
A lone 255 byte starts no valid UTF-8 sequence, so the check answers false.
-
What does this program print?
IO.inspect("é" == "e\u0301")Answer
false
The composed and the decomposed spelling are different binaries, so they are not equal.
-
What does this program print?
text = String.normalize("é", :nfd) IO.inspect(String.codepoints(text))Answer
["e", "́"]
The decomposed form is the letter e and the combining accent, two code points.
-
What does this program print?
IO.inspect(Enum.sort_by(["Zebra", "apple"], &String.downcase/1))Answer
["apple", "Zebra"]
The keys are both lowercase, so the ordinary order puts apple first.
-
What does this program do?
IO.inspect(String.to_charlist(<<0xFF>>))Answer
A UnicodeConversionError, because the byte is not valid UTF-8
The function decodes the characters, and 255 starts no valid sequence.
Article author: Arthur Isaev