Binaries in depth

The bit syntax lesson builds a binary segment by segment. This one walks through the binary: what a bitstring is next to a binary, how a size in a pattern makes a parser, how to read UTF-8 code points out of the bytes, and why a large binary is built from an iolist instead of appended with ++. The functions behind it are in the strings lesson and in Erlang's binary module.

Binary or bitstring

A bitstring is any sequence of bits, and a binary is a bitstring whose length is a multiple of eight. Every binary is a bitstring, but not the other way round. is_binary/1 and is_bitstring/1 tell them apart, and bit_size/1 counts bits while byte_size/1 counts the bytes needed:

erl

1> <<1:3>>. <<1:3>> 2> bit_size(<<1:3>>). 3 3> is_bitstring(<<1:3>>). true 4> is_binary(<<1:3>>). false 5> is_binary(<<1:8>>). true

The shell prints a bitstring with its size in bits, <<1:3>>, because the last byte is only partly filled. A TCP socket and a file are byte streams, so a bitstring that is not byte-aligned has to be padded or handled with the bit syntax before it can be sent.

Sizes in a pattern

In a pattern every segment is a declaration: a fixed size takes that many bits, a variable size takes as many as the variable holds, and a binary segment with no size takes the rest. That is enough to read a header followed by a payload, and the length field is checked by the match itself:

erl

1> <<H, Rest/binary>> = <<1, 2, 3>>. <<1,2,3>> 2> H. 1 3> Rest. <<2,3>> 4> <<N:8, Text:N/binary, Tail/binary>> = <<3, 65, 66, 67, 68>>. <<3,65,66,67,68>> 5> Text. <<"ABC">> 6> Tail. <<"D">>

A size that does not fit the input makes the pattern fail, and the caller sees a badmatch rather than a truncated value. The same form in a function head turns the receiver of a message into a parser: a clause per shape, no manual index.

Walking a binary

A recursive function with an empty binary as its base case visits every byte. Each step matches the byte and the rest, so the recursion is a loop over the binary. The call here is not in tail position, because 1 + count(Rest) adds after it returns, so the stack grows with the input; the recursion lesson shows the accumulator form, which runs in constant space.

walk.erl

-module(walk). -export([main/0, count/1]). count(<<>>) -> 0; count(<<_Byte:8, Rest/binary>>) -> 1 + count(Rest). main() -> Bin = <<1, 2, 3, 4>>, io:format("bytes: ~p~n", [count(Bin)]), io:format("bit size: ~p~n", [bit_size(Bin)]).

erlc walk.erl

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

bytes: 4 bit size: 32

byte_size/1 would answer the first line in one call, and a real parser uses it when it can. The walk is still the shape of every parser that reads a variable field: match what you know, hand the rest to the next clause.

UTF-8 code points

A utf8 segment takes one character, whatever its byte length, and returns its code point. Walking a UTF-8 binary with that segment decodes the text without a library call, and the list of code points prints as the text again because a string is a list of codes:

chars.erl

-module(chars). -export([main/0, codepoints/1]). codepoints(<<>>) -> []; codepoints(<<Char/utf8, Rest/binary>>) -> [Char | codepoints(Rest)]. main() -> Bin = <<"héllo"/utf8>>, io:format("~p~n", [codepoints(Bin)]).

erlc chars.erl

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

"héllo"

The result is a list of code points, not bytes: the five characters of the word, with é as 233. The byte form needs six bytes, as the strings lesson shows. The encoding lesson covers unicode:characters_to_binary/1 for text that must be encoded again.

Building without copying

A binary is immutable, so appending to one with <<Acc/binary, X>> copies the whole accumulator on every step. A loop that adds a byte n times costs n squared bytes of copying. The iolist is the answer: build a list of pieces, then flatten it once. A piece may be a byte, a string, a binary or another list, and iolist_size/1 gives the size of the result before it is made:

join.erl

-module(join). -export([main/0]). main() -> Parts = [<<"one">>, " two", [32, "three"]], Flat = iolist_to_binary(Parts), io:format("~p~n", [Flat]), io:format("~p~n", [iolist_size(Parts)]).

erlc join.erl

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

<<"one two three">> 13

The list holds a binary, a string and a list of a code and a string; the flattening is one pass, and the intermediate pieces are never copied into a growing binary. A logger, a JSON encoder and an HTTP response all build their body this way, and io_lib:format/2 returns an iolist for the same reason.

The binary module

binary:split/3, binary:match/2, binary:part/3 and binary:copy/1 work on bytes without converting to a list. Splitting a comma-separated binary with the global option returns one binary per piece:

erl

1> binary:split(<<"a,b,c">>, <<",">>, [global]). [<<"a">>,<<"b">>,<<"c">>] 2> binary:match(<<"hello">>, <<"ll">>). {2,2} 3> binary:part(<<"hello">>, 2, 2). <<"ll">>

binary:match/2 answers {Start, Length} and nomatch when the pattern is absent; the position counts bytes from zero. These functions are the byte-level companions of the string module, which works on characters. The encoding and sockets lessons use both.

Questions

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

  1. What is the difference between a binary and a bitstring?

    Answer

    A binary is a bitstring whose length is a multiple of eight

    Every binary is a bitstring, and a bitstring of 3 bits is not a binary because it does not fill whole bytes.

  2. What does bit_size(<<1:3>>) return?

    Answer

    3

    The segment declares three bits, so the bitstring holds three bits.

  3. What does is_binary(<<1:3>>) return?

    Answer

    false

    The bitstring is not byte-aligned, so it is not a binary.

  4. In <<H, Rest/binary>> = <<1, 2, 3>>, what does Rest hold?

    Answer

    <<2,3>>

    The first segment takes the first byte and the rest segment takes the remaining two.

  5. Why is <<Acc/binary, X>> in a loop expensive?

    Answer

    It copies the whole accumulator on every step

    A binary is immutable, so appending builds a new binary with a copy of the old one each time.

  6. What does binary:split(<<"a,b">>, <<",">>, [global]) return?

    Answer

    [<<"a">>,<<"b">>]

    The split returns one binary per piece; the pieces are binaries, not strings.

  7. What does <<C/utf8>> do in a pattern?

    Answer

    Takes one character of one to four bytes and binds its code point

    A utf8 segment reads one encoded character and gives its Unicode code point.

  8. What does this module print? -module(q1). -export([main/0, count/1]). count(<<>>) -> 0; count(<<_Byte:8, Rest/binary>>) -> 1 + count(Rest). main() -> io:format("~p~n", [count(<<1, 2, 3>>)]).

    Answer

    3

    Each step takes one byte, so the binary of three bytes gives 3.

  9. What does this module print? -module(q2). -export([main/0, codepoints/1]). codepoints(<<>>) -> []; codepoints(<<Char/utf8, Rest/binary>>) -> [Char | codepoints(Rest)]. main() -> io:format("~p~n", [codepoints(<<"ab">>)]).

    Answer

    "ab"

    The answer is a list of the code points 97 and 98, and ~p prints a printable code list as a string.

  10. What does this module print? -module(q3). -export([main/0]). main() -> Parts = [<<"ab">>, "cd"], io:format("~p~n", [byte_size(iolist_to_binary(Parts))]).

    Answer

    4

    The iolist flattens to the four bytes of abcd.

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