20012016 Ericsson AB. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ei Jakob Cederlund Kent Boortz 1 Kenneth Lundin 2000-11-27 PA1 ei.xml
ei Routines for handling the Erlang binary term format.

The library ei contains macros and functions to encode and decode the Erlang binary term format.

ei allows you to convert atoms, lists, numbers, and binaries to and from the binary format. This is useful when writing port programs and drivers. ei uses a given buffer, no dynamic memory (except ei_decode_fun()) and is often quite fast.

ei also handles C-nodes, C-programs that talks Erlang distribution with Erlang nodes (or other C-nodes) using the Erlang distribution format. The difference between ei and erl_interface is that ei uses the binary format directly when sending and receiving terms. It is also thread safe, and using threads, one process can handle multiple C-nodes. The erl_interface library is built on top of ei, but of legacy reasons, it does not allow for multiple C-nodes. In general, ei is the preferred way of doing C-nodes.

The decode and encode functions use a buffer and an index into the buffer, which points at the point where to encode and decode. The index is updated to point right after the term encoded/decoded. No checking is done whether the term fits in the buffer or not. If encoding goes outside the buffer, the program can crash.

All functions take two parameters:

buf is a pointer to the buffer where the binary data is or will be.

index is a pointer to an index into the buffer. This parameter is incremented with the size of the term decoded/encoded.

The data is thus at buf[*index] when an ei function is called.

All encode functions assume that the buf and index parameters point to a buffer large enough for the data. To get the size of an encoded term, without encoding it, pass NULL instead of a buffer pointer. Parameter index is incremented, but nothing will be encoded. This is the way in ei to "preflight" term encoding.

There are also encode functions that use a dynamic buffer. It is often more convenient to use these to encode data. All encode functions comes in two versions; those starting with ei_x use a dynamic buffer.

All functions return 0 if successful, otherwise -1 (for example, if a term is not of the expected type, or the data to decode is an invalid Erlang term).

Some of the decode functions need a pre-allocated buffer. This buffer must be allocated large enough, and for non-compound types the ei_get_type() function returns the size required (notice that for strings an extra byte is needed for the NULL-terminator).

Data Types erlang_char_encoding typedef enum { ERLANG_ASCII = 1, ERLANG_LATIN1 = 2, ERLANG_UTF8 = 4 } erlang_char_encoding;

The character encodings used for atoms. ERLANG_ASCII represents 7-bit ASCII. Latin-1 and UTF-8 are different extensions of 7-bit ASCII. All 7-bit ASCII characters are valid Latin-1 and UTF-8 characters. ASCII and Latin-1 both represent each character by one byte. An UTF-8 character can consist of 1-4 bytes. Notice that these constants are bit-flags and can be combined with bitwise OR.

intei_decode_atom(const char *buf, int *index, char *p) Decode an atom.

Decodes an atom from the binary format. The NULL-terminated name of the atom is placed at p. At most MAXATOMLEN bytes can be placed in the buffer.

intei_decode_atom_as(const char *buf, int *index, char *p, int plen, erlang_char_encoding want, erlang_char_encoding* was, erlang_char_encoding* result) Decode an atom.

Decodes an atom from the binary format. The NULL-terminated name of the atom is placed in buffer at p of length plen bytes.

The wanted string encoding is specified by want. The original encoding used in the binary format (Latin-1 or UTF-8) can be obtained from *was. The encoding of the resulting string (7-bit ASCII, Latin-1, or UTF-8) can be obtained from *result. Both was and result can be NULL. *result can differ from want if want is a bitwise OR'd combination like ERLANG_LATIN1|ERLANG_UTF8 or if *result turns out to be pure 7-bit ASCII (compatible with both Latin-1 and UTF-8).

This function fails if the atom is too long for the buffer or if it cannot be represented with encoding want.

This function was introduced in Erlang/OTP R16 as part of a first step to support UTF-8 atoms.

intei_decode_bignum(const char *buf, int *index, mpz_t obj) Decode a GMP arbitrary precision integer.

Decodes an integer in the binary format to a GMP mpz_t integer. To use this function, the ei library must be configured and compiled to use the GMP library.

intei_decode_binary(const char *buf, int *index, void *p, long *len) Decode a binary.

Decodes a binary from the binary format. Parameter len is set to the actual size of the binary. Notice that ei_decode_binary() assumes that there is enough room for the binary. The size required can be fetched by ei_get_type().

intei_decode_boolean(const char *buf, int *index, int *p) Decode a boolean.

Decodes a boolean value from the binary format. A boolean is actually an atom, true decodes 1 and false decodes 0.

intei_decode_char(const char *buf, int *index, char *p) Decode an 8-bit integer between 0-255.

Decodes a char (8-bit) integer between 0-255 from the binary format. For historical reasons the returned integer is of type char. Your C code is to consider the returned value to be of type unsigned char even if the C compilers and system can define char to be signed.

intei_decode_double(const char *buf, int *index, double *p) Decode a double.

Decodes a double-precision (64-bit) floating point number from the binary format.

intei_decode_ei_term(const char* buf, int* index, ei_term* term) Decode a term, without previous knowledge of type.

Decodes any term, or at least tries to. If the term pointed at by *index in buf fits in the term union, it is decoded, and the appropriate field in term->value is set, and *index is incremented by the term size.

The function returns 1 on successful decoding, -1 on error, and 0 if the term seems alright, but does not fit in the term structure. If 1 is returned, the index is incremented, and term contains the decoded term.

The term structure contains the arity for a tuple or list, size for a binary, string, or atom. It contains a term if it is any of the following: integer, float, atom, pid, port, or ref.

intei_decode_fun(const char *buf, int *index, erlang_fun *p) voidfree_fun(erlang_fun* f) Decode a fun.

Decodes a fun from the binary format. Parameter p is to be NULL or point to an erlang_fun structure. This is the only decode function that allocates memory. When the erlang_fun is no longer needed, it is to be freed with free_fun. (This has to do with the arbitrary size of the environment for a fun.)

intei_decode_list_header(const char *buf, int *index, int *arity) Decode a list.

Decodes a list header from the binary format. The number of elements is returned in arity. The arity+1 elements follow (the last one is the tail of the list, normally an empty list). If arity is 0, it is an empty list.

Notice that lists are encoded as strings if they consist entirely of integers in the range 0..255. This function do not decode such strings, use ei_decode_string() instead.

intei_decode_long(const char *buf, int *index, long *p) Decode integer.

Decodes a long integer from the binary format. If the code is 64 bits, the function ei_decode_long() is the same as ei_decode_longlong().

intei_decode_longlong(const char *buf, int *index, long long *p) Decode integer.

Decodes a GCC long long or Visual C++ __int64 (64-bit) integer from the binary format. This function is missing in the VxWorks port.

intei_decode_map_header(const char *buf, int *index, int *arity) Decode a map.

Decodes a map header from the binary format. The number of key-value pairs is returned in *arity. Keys and values follow in this order: K1, V1, K2, V2, ..., Kn, Vn. This makes a total of arity*2 terms. If arity is zero, it is an empty map. A correctly encoded map does not have duplicate keys.

intei_decode_pid(const char *buf, int *index, erlang_pid *p) Decode a pid.

Decodes a process identifier (pid) from the binary format.

intei_decode_port(const char *buf, int *index, erlang_port *p) Decode a port.

Decodes a port identifier from the binary format.

intei_decode_ref(const char *buf, int *index, erlang_ref *p) Decode a reference.

Decodes a reference from the binary format.

intei_decode_string(const char *buf, int *index, char *p) Decode a string.

Decodes a string from the binary format. A string in Erlang is a list of integers between 0 and 255. Notice that as the string is just a list, sometimes lists are encoded as strings by term_to_binary/1, even if it was not intended.

The string is copied to p, and enough space must be allocated. The returned string is NULL-terminated, so you must add an extra byte to the memory requirement.

intei_decode_term(const char *buf, int *index, void *t) Decode a ETERM.

Decodes a term from the binary format. The term is return in t as a ETERM*, so t is actually an ETERM** (see erl_eterm). The term is later to be deallocated.

Notice that this function is located in the Erl_Interface library.

intei_decode_trace(const char *buf, int *index, erlang_trace *p) Decode a trace token.

Decodes an Erlang trace token from the binary format.

intei_decode_tuple_header(const char *buf, int *index, int *arity) Decode a tuple.

Decodes a tuple header, the number of elements is returned in arity. The tuple elements follow in order in the buffer.

intei_decode_ulong(const char *buf, int *index, unsigned long *p) Decode unsigned integer.

Decodes an unsigned long integer from the binary format. If the code is 64 bits, the function ei_decode_ulong() is the same as ei_decode_ulonglong().

intei_decode_ulonglong(const char *buf, int *index, unsigned long long *p) Decode unsigned integer.

Decodes a GCC unsigned long long or Visual C++ unsigned __int64 (64-bit) integer from the binary format. This function is missing in the VxWorks port.

intei_decode_version(const char *buf, int *index, int *version) Decode an empty list (nil).

Decodes the version magic number for the Erlang binary term format. It must be the first token in a binary term.

intei_encode_atom(char *buf, int *index, const char *p) intei_encode_atom_len(char *buf, int *index, const char *p, int len) intei_x_encode_atom(ei_x_buff* x, const char *p) intei_x_encode_atom_len(ei_x_buff* x, const char *p, int len) Encode an atom.

Encodes an atom in the binary format. Parameter p is the name of the atom in Latin-1 encoding. Only up to MAXATOMLEN-1 bytes are encoded. The name is to be NULL-terminated, except for the ei_x_encode_atom_len() function.

intei_encode_atom_as(char *buf, int *index, const char *p, erlang_char_encoding from_enc, erlang_char_encoding to_enc) intei_encode_atom_len_as(char *buf, int *index, const char *p, int len, erlang_char_encoding from_enc, erlang_char_encoding to_enc) intei_x_encode_atom_as(ei_x_buff* x, const char *p, erlang_char_encoding from_enc, erlang_char_encoding to_enc) intei_x_encode_atom_len_as(ei_x_buff* x, const char *p, int len, erlang_char_encoding from_enc, erlang_char_encoding to_enc) Encode an atom.

Encodes an atom in the binary format with character encoding to_enc (Latin-1 or UTF-8). Parameter p is the name of the atom with character encoding from_enc (ASCII, Latin-1, or UTF-8). The name must either be NULL-terminated or a function variant with a len parameter must be used. If to_enc is set to the bitwise OR'd combination (ERLANG_LATIN1|ERLANG_UTF8), UTF-8 encoding is only used if the atom string cannot be represented in Latin-1 encoding.

The encoding fails if p is an invalid string in encoding from_enc, if the string is too long, or if it cannot be represented with character encoding to_enc.

These functions were introduced in Erlang/OTP R16 as part of a first step to support UTF-8 atoms. Atoms encoded with ERLANG_UTF8 cannot be decoded by earlier releases than R16.

intei_encode_bignum(char *buf, int *index, mpz_t obj) intei_x_encode_bignum(ei_x_buff *x, mpz_t obj) Encode an arbitrary precision integer.

Encodes a GMP mpz_t integer to binary format. To use this function, the ei library must be configured and compiled to use the GMP library.

intei_encode_binary(char *buf, int *index, const void *p, long len) intei_x_encode_binary(ei_x_buff* x, const void *p, long len) Encode a binary.

Encodes a binary in the binary format. The data is at p, of len bytes length.

intei_encode_boolean(char *buf, int *index, int p) intei_x_encode_boolean(ei_x_buff* x, int p) Encode a boolean.

Encodes a boolean value as the atom true if p is not zero, or false if p is zero.

intei_encode_char(char *buf, int *index, char p) intei_x_encode_char(ei_x_buff* x, char p) Encode an 8-bit integer between 0-255.

Encodes a char (8-bit) as an integer between 0-255 in the binary format. For historical reasons the integer argument is of type char. Your C code is to consider the specified argument to be of type unsigned char even if the C compilers and system may define char to be signed.

intei_encode_double(char *buf, int *index, double p) intei_x_encode_double(ei_x_buff* x, double p) Encode a double float.

Encodes a double-precision (64-bit) floating point number in the binary format.

Returns -1 if the floating point number is not finite.

intei_encode_empty_list(char* buf, int* index) intei_x_encode_empty_list(ei_x_buff* x) Encode an empty list (nil).

Encodes an empty list. It is often used at the tail of a list.

intei_encode_fun(char *buf, int *index, const erlang_fun *p) intei_x_encode_fun(ei_x_buff* x, const erlang_fun* fun) Encode a fun.

Encodes a fun in the binary format. Parameter p points to an erlang_fun structure. The erlang_fun is not freed automatically, the free_fun is to be called if the fun is not needed after encoding.

intei_encode_list_header(char *buf, int *index, int arity) intei_x_encode_list_header(ei_x_buff* x, int arity) Encode a list.

Encodes a list header, with a specified arity. The next arity+1 terms are the elements (actually its arity cons cells) and the tail of the list. Lists and tuples are encoded recursively, so that a list can contain another list or tuple.

For example, to encode the list [c, d, [e | f]]:

ei_encode_list_header(buf, &i, 3);
ei_encode_atom(buf, &i, "c");
ei_encode_atom(buf, &i, "d");
ei_encode_list_header(buf, &i, 1);
ei_encode_atom(buf, &i, "e");
ei_encode_atom(buf, &i, "f");
ei_encode_empty_list(buf, &i);

It may seem that there is no way to create a list without knowing the number of elements in advance. But indeed there is a way. Notice that the list [a, b, c] can be written as [a | [b | [c]]]. Using this, a list can be written as conses.

To encode a list, without knowing the arity in advance:

while (something()) {
    ei_x_encode_list_header(&x, 1);
    ei_x_encode_ulong(&x, i); /* just an example */
}
ei_x_encode_empty_list(&x);
intei_encode_long(char *buf, int *index, long p) intei_x_encode_long(ei_x_buff* x, long p) Encode integer.

Encodes a long integer in the binary format. If the code is 64 bits, the function ei_encode_long() is the same as ei_encode_longlong().

intei_encode_longlong(char *buf, int *index, long long p) intei_x_encode_longlong(ei_x_buff* x, long long p) Encode integer.

Encodes a GCC long long or Visual C++ __int64 (64-bit) integer in the binary format. This function is missing in the VxWorks port.

intei_encode_map_header(char *buf, int *index, int arity) intei_x_encode_map_header(ei_x_buff* x, int arity) Encode a map.

Encodes a map header, with a specified arity. The next arity*2 terms encoded will be the keys and values of the map encoded in the following order: K1, V1, K2, V2, ..., Kn, Vn.

For example, to encode the map #{a => "Apple", b => "Banana"}:

ei_x_encode_map_header(&x, 2);
ei_x_encode_atom(&x, "a");
ei_x_encode_string(&x, "Apple");
ei_x_encode_atom(&x, "b");
ei_x_encode_string(&x, "Banana");

A correctly encoded map cannot have duplicate keys.

intei_encode_pid(char *buf, int *index, const erlang_pid *p) intei_x_encode_pid(ei_x_buff* x, const erlang_pid *p) Encode a pid.

Encodes an Erlang process identifier (pid) in the binary format. Parameter p points to an erlang_pid structure (which should have been obtained earlier with ei_decode_pid()).

intei_encode_port(char *buf, int *index, const erlang_port *p) intei_x_encode_port(ei_x_buff* x, const erlang_port *p) Encode a port.

Encodes an Erlang port in the binary format. Parameter p points to a erlang_port structure (which should have been obtained earlier with ei_decode_port()).

intei_encode_ref(char *buf, int *index, const erlang_ref *p) intei_x_encode_ref(ei_x_buff* x, const erlang_ref *p) Encode a ref.

Encodes an Erlang reference in the binary format. Parameter p points to a erlang_ref structure (which should have been obtained earlier with ei_decode_ref()).

intei_encode_string(char *buf, int *index, const char *p) intei_encode_string_len(char *buf, int *index, const char *p, int len) intei_x_encode_string(ei_x_buff* x, const char *p) intei_x_encode_string_len(ei_x_buff* x, const char* s, int len) Encode a string.

Encodes a string in the binary format. (A string in Erlang is a list, but is encoded as a character array in the binary format.) The string is to be NULL-terminated, except for the ei_x_encode_string_len() function.

intei_encode_term(char *buf, int *index, void *t) intei_x_encode_term(ei_x_buff* x, void *t) Encode an erl_interface term.

Encodes an ETERM, as obtained from erl_interface. Parameter t is actually an ETERM pointer. This function does not free the ETERM.

intei_encode_trace(char *buf, int *index, const erlang_trace *p) intei_x_encode_trace(ei_x_buff* x, const erlang_trace *p) Encode a trace token.

Encodes an Erlang trace token in the binary format. Parameter p points to a erlang_trace structure (which should have been obtained earlier with ei_decode_trace()).

intei_encode_tuple_header(char *buf, int *index, int arity) intei_x_encode_tuple_header(ei_x_buff* x, int arity) Encode a tuple.

Encodes a tuple header, with a specified arity. The next arity terms encoded will be the elements of the tuple. Tuples and lists are encoded recursively, so that a tuple can contain another tuple or list.

For example, to encode the tuple {a, {b, {}}}:

ei_encode_tuple_header(buf, &i, 2);
ei_encode_atom(buf, &i, "a");
ei_encode_tuple_header(buf, &i, 2);
ei_encode_atom(buf, &i, "b");
ei_encode_tuple_header(buf, &i, 0);
intei_encode_ulong(char *buf, int *index, unsigned long p) intei_x_encode_ulong(ei_x_buff* x, unsigned long p) Encode unsigned integer.

Encodes an unsigned long integer in the binary format. If the code is 64 bits, the function ei_encode_ulong() is the same as ei_encode_ulonglong().

intei_encode_ulonglong(char *buf, int *index, unsigned long long p) intei_x_encode_ulonglong(ei_x_buff* x, unsigned long long p) Encode unsigned integer.

Encodes a GCC unsigned long long or Visual C++ unsigned __int64 (64-bit) integer in the binary format. This function is missing in the VxWorks port.

intei_encode_version(char *buf, int *index) intei_x_encode_version(ei_x_buff* x) Encode version.

Encodes a version magic number for the binary format. Must be the first token in a binary term.

intei_get_type(const char *buf, const int *index, int *type, int *size) Fetch the type and size of an encoded term.

Returns the type in type and size in size of the encoded term. For strings and atoms, size is the number of characters not including the terminating NULL. For binaries, size is the number of bytes. For lists and tuples, size is the arity of the object. For other types, size is 0. In all cases, index is left unchanged.

intei_print_term(FILE* fp, const char* buf, int* index) intei_s_print_term(char** s, const char* buf, int* index) Print a term in clear text.

Prints a term, in clear text, to the file specified by fp, or the buffer pointed to by s. It tries to resemble the term printing in the Erlang shell.

In ei_s_print_term(), parameter s is to point to a dynamically (malloc) allocated string of BUFSIZ bytes or a NULL pointer. The string can be reallocated (and *s can be updated) by this function if the result is more than BUFSIZ characters. The string returned is NULL-terminated.

The return value is the number of characters written to the file or string, or -1 if buf[index] does not contain a valid term. Unfortunately, I/O errors on fp is not checked.

Argument index is updated, that is, this function can be viewed as a decode function that decodes a term into a human-readable format.

voidei_set_compat_rel(release_number) Set the ei library in compatibility mode. unsigned release_number;

By default, the ei library is only guaranteed to be compatible with other Erlang/OTP components from the same release as the ei library itself. For example, ei from Erlang/OTP R10 is not compatible with an Erlang emulator from Erlang/OTP R9 by default.

A call to ei_set_compat_rel(release_number) sets the ei library in compatibility mode of release release_number. Valid range of release_number is [7, current release]. This makes it possible to communicate with Erlang/OTP components from earlier releases.

If this function is called, it can only be called once and must be called before any other functions in the ei library are called.

You can run into trouble if this feature is used carelessly. Always ensure that all communicating components are either from the same Erlang/OTP release, or from release X and release Y where all components from release Y are in compatibility mode of release X.

intei_skip_term(const char* buf, int* index) Skip a term.

Skips a term in the specified buffer; recursively skips elements of lists and tuples, so that a full term is skipped. This is a way to get the size of an Erlang term.

buf is the buffer.

index is updated to point right after the term in the buffer.

This can be useful when you want to hold arbitrary terms: skip them and copy the binary term data to some buffer.

Returns 0 on success, otherwise -1.

intei_x_append(ei_x_buff* x, const ei_x_buff* x2) intei_x_append_buf(ei_x_buff* x, const char* buf, int len) Append a buffer at the end.

Appends data at the end of buffer x.

intei_x_format(ei_x_buff* x, const char* fmt, ...) intei_x_format_wo_ver(ei_x_buff* x, const char *fmt, ... ) Format a term from a format string and parameters.

Formats a term, given as a string, to a buffer. Works like a sprintf for Erlang terms. fmt contains a format string, with arguments like ~d, to insert terms from variables. The following formats are supported (with the C types given):

~a  An atom, char*
~c  A character, char
~s  A string, char*
~i  An integer, int
~l  A long integer, long int
~u  A unsigned long integer, unsigned long int
~f  A float, float
~d  A double float, double float
~p  An Erlang pid, erlang_pid*

For example, to encode a tuple with some stuff:

ei_x_format("{~a,~i,~d}", "numbers", 12, 3.14159)
encodes the tuple {numbers,12,3.14159}

ei_x_format_wo_ver() formats into a buffer, without the initial version byte.

intei_x_free(ei_x_buff* x) Free a buffer.

Frees an ei_x_buff buffer. The memory used by the buffer is returned to the OS.

intei_x_new(ei_x_buff* x) intei_x_new_with_version(ei_x_buff* x) Allocate a new buffer.

Allocates a new ei_x_buff buffer. The fields of the structure pointed to by parameter x is filled in, and a default buffer is allocated. ei_x_new_with_version() also puts an initial version byte, which is used in the binary format (so that ei_x_encode_version() will not be needed.)

Debug Information

Some tips on what to check when the emulator does not seem to receive the terms that you send:

Be careful with the version header, use ei_x_new_with_version() when appropriate. Turn on distribution tracing on the Erlang node. Check the result codes from ei_decode_-calls.
See Also

erl_eterm