Encodings and Unicode

Text in Erlang is a binary of UTF-8 bytes or a list of code points, and the two are not the same length. A function that counts, cuts or compares them must know which one it holds. This lesson builds a UTF-8 binary, counts its characters and its bytes, splits one character by accident, and composes an accent back into one code point.

UTF-8 binaries

A binary literal with a non-ASCII character holds the UTF-8 bytes of that character, and the /utf8 in the literal makes the source encoding explicit. The strings lesson shows the list form; this module keeps text as a binary and converts with the unicode module at the edges. It prints the byte count, the character count, the code points, and the text back again:

text.erl

-module(text). -export([main/0, upper/1, codepoints/1, from_codepoints/1]). upper(Bin) -> string:uppercase(Bin). codepoints(Bin) -> unicode:characters_to_list(Bin). from_codepoints(List) -> unicode:characters_to_binary(List). main() -> Text = <<"café"/utf8>>, io:format("~p~n", [byte_size(Text)]), io:format("~p~n", [string:length(Text)]), io:format("~w~n", [codepoints(Text)]), io:format("~tp~n", [from_codepoints([99, 97, 102, 233])]), io:format("~tp~n", [upper(Text)]).

erlc text.erl

erl -noshell -eval 'text:main(), halt().'

5 4 [99,97,102,233] <<"café"/utf8>> <<"CAFÉ"/utf8>>

The five bytes and the four characters are the whole lesson in two lines. The ~w directive prints the code points as numbers, and ~tp prints a UTF-8 binary in the readable form; plain ~p treats every byte as Latin-1 and prints <<"café">> for the same value.

Characters and bytes

byte_size/1 counts the bytes of the binary and string:length/1 counts the characters. A program that validates a field by byte length accepts fewer characters than the user sees, and one that cuts a fixed number of bytes can land in the middle of a character. The shell shows both counts:

erl

1> string:length(<<"café"/utf8>>). 4 2> byte_size(<<"café"/utf8>>). 5 3> io:format("~w~n", [unicode:characters_to_list(<<"café"/utf8>>)]). [99,97,102,233] ok

The code points are c, a, f and é; the last one is the single code point 233 because the source wrote it precomposed. The binaries in depth lesson shows the pattern that reads such a binary segment by segment.

The slice that splits a character

binary:part/3 counts bytes, so a cut at byte 4 of "café" keeps three letters and the first byte of the two-byte é. The result is still a binary, and the mistake is easy to miss until a decoder reaches it:

broken.erl

-module(broken). -export([main/0]). main() -> Text = <<"café"/utf8>>, Cut = binary:part(Text, 0, 4), io:format("~w~n", [Cut]), io:format("~w~n", [unicode:characters_to_list(Cut)]).

erlc broken.erl

erl -noshell -eval 'broken:main(), halt().'

<<99,97,102,195>> {incomplete,[99,97,102],<<195>>}

The decoder does not pretend: it answers incomplete, the characters it could read and the byte that had no partner. A program that ignores the tuple and treats it as a list stores broken text, and the break surfaces in a browser or a database much later. Cut on a character boundary with string:slice/3, or convert to code points, slice the list and convert back.

Normalization

Two binaries can look identical and compare unequal: é is one code point in one source and e followed by a combining accent in another. NFC composition turns the second form into the first, which is what a comparison or a unique index needs:

nfc.erl

-module(nfc). -export([main/0]). main() -> Decomposed = <<"cafe", 769/utf8>>, io:format("~tp~n", [Decomposed]), io:format("~tp~n", [unicode:characters_to_nfc_binary(Decomposed)]).

erlc nfc.erl

erl -noshell -eval 'nfc:main(), halt().'

<<99,97,102,101,204,129>> <<"café"/utf8>>

The first line is six bytes for five characters: e and the combining mark 769 each take their own. The second is the composed form. A program that stores user text normalizes it once on input, with unicode:characters_to_nfc_binary/1, so two spellings of the same word meet as one value.

Rules of thumb

Keep a binary for text that arrives and leaves, because that is what a socket, a file and JSON carry. Convert to a list of code points only where a character operation is easier, and convert back before the value leaves. Never mix Latin-1 and UTF-8 in one program: the fix for broken text is at the boundary, not in the logic. Old code that mentions latin1 is a place to convert once, then forget the encoding; the term formats lesson in this chapter keeps the same bytes when a term is stored.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How many bytes does <<"café"/utf8>> hold?

    Answer

    5

    The é needs two UTF-8 bytes, so four characters take five bytes.

  2. What does string:length(<<"café"/utf8>>) answer?

    Answer

    4

    The string module counts characters, and café has four of them.

  3. Why do string:length/1 and byte_size/1 disagree here?

    Answer

    Length counts characters, byte_size counts bytes

    One non-ASCII character takes several bytes, so characters and bytes are different numbers.

  4. What does unicode:characters_to_list(<<"café"/utf8>>) answer?

    Answer

    [99,97,102,233]

    It answers a list of the four code points; the shell may print that printable list as "café".

  5. What does this module print? -module(q1). -export([main/0]). main() -> io:format("~p~n", [byte_size(<<"é"/utf8>>)]).

    Answer

    2

    The single character é takes two bytes in UTF-8.

  6. What does this module print? -module(q2). -export([main/0]). main() -> io:format("~p~n", [string:length(<<"héllo"/utf8>>)]).

    Answer

    5

    There are five characters; the é is one character even though it takes two bytes.

  7. What does this module print? -module(q3). -export([main/0]). main() -> io:format("~w~n", [unicode:characters_to_list(<<"é"/utf8>>)]).

    Answer

    [233]

    ~w prints the list of code points, and é is the single code point 233.

  8. What does this module print? -module(q4). -export([main/0]). main() -> io:format("~w~n", [binary:part(<<"café"/utf8>>, 0, 4)]).

    Answer

    <<99,97,102,195>>

    The cut takes four bytes, and the fourth is the first half of the two-byte é.

  9. What does unicode:characters_to_list/1 answer for a binary cut in the middle of a character?

    Answer

    {incomplete, Read, Rest}

    The decoder reports the characters it read and the bytes it could not complete.

  10. What is NFC normalization for?

    Answer

    Making two spellings of one character compare equal

    NFC composes a base letter and a combining mark into one code point, so equal words are equal binaries.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev