ei(3)

πŸ“¦
version 29.0.6 Β· 2 versions
, in nixos 26.05, nixpkgs unstable, ubuntu stonking

πŸ’– ei(3) πŸ’–

okay bestie, this is the manual page for ei β€” Routines for handling the Erlang binary term format. she's long, she's a little unhinged, and she's gonna change your port-programming life. strap in πŸ¦‹βœ¨


πŸ“› NAME

ei β€” routines for handling the Erlang binary term format. that's it. that's the girl. πŸ’…


🌸 DESCRIPTION

the library ei is packed with macros and functions that encode and decode the Erlang binary term format. ✨

ei lets you flip atoms, lists, numbers, and binaries to and from the binary format. lowkey essential when you're writing port programs and drivers. ei uses a given buffer, no dynamic memory (except for ei_decode_fun() β€” more on her later), and is often quite fast. no cap. πŸ”₯

ei also handles C-nodes β€” that's C-programs that talk Erlang distribution with Erlang nodes (or other C-nodes) using the Erlang distribution format. and get this: the ei library is thread safe, so if you're using threads, one process can handle multiple C-nodes. main character energy fr. πŸ‘‘

the decode and encode functions use a buffer and an index into the buffer, like a little bookmark πŸŽ€ that points at the spot where you're encoding and decoding. the index gets updated to point right after the term you encoded/decoded. and here's the thing β€” there is no checking whether the term fits in the buffer or not. if encoding goes outside the buffer, the program can crash. like, will crash. πŸ’€

⚠️ bestie pls. no bounds checking. the buffer is your problem. keep her big enough.

all functions take two parameters:

  • buf β€” a pointer to the buffer where the binary data is (or will be).
  • index β€” a pointer to an index into the buffer. this one gets incremented with the size of the term decoded/encoded.

so when an ei function is called, the data is at buf[*index]. periodt. πŸ’«

every encode function assumes that buf and index point to a buffer that is large enough for the data. and note β€” the binary term format uses variable-length encoding, so different values can require different amounts of space. like, smaller integer values can be more compact than larger ones. iconic behavior honestly. πŸŽ€

to get the size of an encoded term without encoding it, pass NULL instead of a buffer pointer. parameter index is still incremented, but nothing will actually be encoded. this is the way to "preflight" term encoding in ei. ✈️

there are also encode functions that use a dynamic buffer. it's often more convenient to use these to encode data. all encode functions come in two versions; the ones starting with ei_x_ use a dynamic buffer of type ei_x_buff. slay.

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). yes bestie, classic C "did it work" energy. πŸ™ˆ

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

  • ei_term β€” a struct written by ei_decode_ei_term(). the ei_type field is the type of the term, which equals what ei_get_type() sets *type to.
typedef struct {
    char ei_type;
    int arity;
    int size;
    union {
     long i_val;
     double d_val;
     char atom_name[MAXATOMLEN_UTF8];
     erlang_pid pid;
     erlang_port port;
     erlang_ref ref;
    } value;
} ei_term;
  • ei_x_buff β€” a dynamically resized buffer. it's a struct with two fields of interest for the user:
    • char *buff β€” pointer to the dynamically allocated buffer.
    • int index β€” the offset to the next byte to write, which also equals the amount of bytes currently written.

an ei_x_buff is initialized by calling either ei_x_new() or ei_x_new_with_version(). the memory used by an initialized ei_x_buff is released by calling ei_x_free(). 🫢

  • erlang_char_encoding β€” the character encodings used for atoms.
typedef enum {
    ERLANG_ASCII = 1,
    ERLANG_LATIN1 = 2,
    ERLANG_UTF8 = 4
} erlang_char_encoding;

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. πŸŽ€

  • erlang_fun β€” opaque data type representing an Erlang fun.
  • erlang_pid β€” opaque data type representing an Erlang process identifier.
  • erlang_port β€” opaque data type representing an Erlang port identifier.
  • erlang_ref β€” opaque data type representing an Erlang reference.
  • erlang_trace β€” opaque data type representing an Erlang sequential trace token.

βš–οΈ ei_cmp_pids()

int ei_cmp_pids(erlang_pid *a, erlang_pid *b);

compare two process identifiers. the comparison is done the same way Erlang does it. πŸ’…

returns 0 if a and b are equal. returns a value less than 0 if a compares as less than b. returns a value larger than 0 if a compares as larger than b.

available since OTP 23.0 ✨


βš–οΈ ei_cmp_ports()

int ei_cmp_ports(erlang_port *a, erlang_port *b);

compare two port identifiers. the comparison is done the same way Erlang does it.

returns 0 if a and b are equal. returns a value less than 0 if a compares as less than b. returns a value larger than 0 if a compares as larger than b.

available since OTP 23.0 ✨


βš–οΈ ei_cmp_refs()

int ei_cmp_refs(erlang_ref *a, erlang_ref *b);

compare two references. the comparison is done the same way Erlang does it.

returns 0 if a and b are equal. returns a value less than 0 if a compares as less than b. returns a value larger than 0 if a compares as larger than b.

available since OTP 23.0 ✨


πŸ…°οΈ ei_decode_atom()

int ei_decode_atom(const char *buf, int *index, char *p);

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.


πŸ…°οΈβœ¨ ei_decode_atom_as()

int ei_decode_atom_as(const char *buf, int *index, char *p, int plen,
  erlang_char_encoding want, erlang_char_encoding* was, erlang_char_encoding* result);

decodes an atom from the binary format. the NULL-terminated name of the atom is placed in the 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. πŸ¦‹

available since OTP R16B


πŸ”’ ei_decode_bignum()

int ei_decode_bignum(const char *buf, int *index, mpz_t obj);

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. πŸ‘‘


πŸ“¦ ei_decode_binary()

int ei_decode_binary(const char *buf, int *index, void *p, long *len);

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(). πŸ™ˆ


🧡 ei_decode_bitstring()

int ei_decode_bitstring(const char *buf, int *index, const char **pp,
  unsigned int *bitoffsp, size_t *nbitsp);

decodes a bit string from the binary format. ✨

  • pp β€” either NULL or *pp returns a pointer to the first byte of the bit string. the returned bit string is readable as long as the buffer pointed to by buf is readable and not written to.
  • bitoffsp β€” either NULL or *bitoffsp returns the number of unused bits in the first byte pointed to by *pp. the value of *bitoffsp is between 0 and 7. unused bits in the first byte are the most significant bits.
  • nbitsp β€” either NULL or *nbitsp returns the length of the bit string in bits.

returns 0 if it was a bit string term.

the number of bytes pointed to by *pp, which are part of the bit string, is (*bitoffsp + *nbitsp + 7)/8. if (*bitoffsp + *bitsp)%8 > 0 then only (*bitoffsp + *bitsp)%8 bits of the last byte are used. unused bits in the last byte are the least significant bits.

the values of unused bits in the first and last byte are undefined and cannot be relied on. πŸ’€

number of bits may be divisible by 8, which means a binary decodable by ei_decode_binary is also decodable by ei_decode_bitstring.

available since OTP 22.0 πŸŽ€


βœ… ei_decode_boolean()

int ei_decode_boolean(const char *buf, int *index, int *p);

decodes a boolean value from the binary format. a boolean is actually an atom β€” true decodes 1 and false decodes 0. classic erlang moment fr. πŸ’œ


πŸ”€ ei_decode_char()

int ei_decode_char(const char *buf, int *index, char *p);

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. πŸ™ƒ (she's giving ancient-C-vibes, we don't make the rules)


🎯 ei_decode_double()

int ei_decode_double(const char *buf, int *index, double *p);

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


🎁 ei_decode_ei_term()

int ei_decode_ei_term(const char* buf, int* index, ei_term* term);

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. (yes, she has three return values. she's complicated. πŸ’…)

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.


🌟 ei_decode_fun() / free_fun()

int ei_decode_fun(const char *buf, int *index, erlang_fun *p);

void free_fun(erlang_fun* f);

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 β€” she's high maintenance like that.) πŸ’…


🌊 ei_decode_iodata()

int ei_decode_iodata(const char *buf, int *index, int *size, char *outbuf);

to be continued, bestie… the girl isn't done yet πŸ’–πŸ¦‹

Like, it decodes a term of the type iodata(). The iodata/0 term gets flattened and written straight into the buffer that the outbuf argument points at. The byte size of the iodata lands in the integer variable that the size argument points to. Both size and outbuf can totally be set to NULL, no drama. The integer pointed to by the index argument gets updated so it refers to the term following after the iodata/0 term β€” and this happens regardless of the state of the size and outbuf arguments, periodt.

⚠️ Okay so heads up bestie: that buffer pointed to by outbuf must be large enough if you pass a non-NULL value as outbuf. No cap.

You typically wanna call ei_decode_iodata() twice, bestie. First with a non-NULL size argument and a NULL outbuf argument so you can figure out how big the buffer needs to be, and then again to actually do the decoding. But watch out β€” the integer pointed to by index gets updated by the size-determining call too, so you gotta reset it before the second call that does the actual decoding. πŸ™ˆ

Returns 0 on success and -1 on failure. Failure might be either because the encoding of the term is invalid, or because the term isn't of the type iodata/0. On failure, the integer pointed to by the index argument gets updated to refer to the sub term where the failure was detected. πŸ’€

Available since OTP 23.0 ✨


ei_decode_list_header()

int ei_decode_list_header(const char *buf, int *index, int *arity);

Decodes a list header from the binary format. The number of elements comes back in arity. Then arity+1 elements follow (the last one is the tail of the list, which is normally an empty list). If arity is 0, it's an empty list, slay.

πŸ‘€ Notice that lists are encoded as strings if they consist entirely of integers in the range 0..255. This function does not decode such strings β€” use ei_decode_string() instead, okay?

ei_decode_long()

int ei_decode_long(const char *buf, int *index, long *p);

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

ei_decode_longlong()

int ei_decode_longlong(const char *buf, int *index, long long *p);

Decodes a GCC long long or Visual C++ __int64 (64-bit) integer from the binary format.

ei_decode_map_header()

int ei_decode_map_header(const char *buf, int *index, int *arity);

Decodes a map header from the binary format. The number of key-value pairs comes back in *arity. Keys and values follow in this order: K1, V1, K2, V2, ..., Kn, Vn. That makes a total of arity*2 terms. If arity is zero, it's an empty map. And a correctly encoded map does not have duplicate keys. πŸ—ΊοΈ

Available since OTP 17.0 ✨

ei_decode_pid()

int ei_decode_pid(const char *buf, int *index, erlang_pid *p);

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

ei_decode_port()

int ei_decode_port(const char *buf, int *index, erlang_port *p);

Decodes a port identifier from the binary format.

ei_decode_ref()

int ei_decode_ref(const char *buf, int *index, erlang_ref *p);

Decodes a reference from the binary format.

ei_decode_string()

int ei_decode_string(const char *buf, int *index, char *p);

Decodes a string from the binary format. A string in Erlang is a list of integers between 0 and 255. And notice β€” because the string is just a list, sometimes lists get encoded as strings by term_to_binary/1, even if that wasn't the intent at all. 😭

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

ei_decode_trace()

int ei_decode_trace(const char *buf, int *index, erlang_trace *p);

Decodes an Erlang trace token from the binary format.

ei_decode_tuple_header()

int ei_decode_tuple_header(const char *buf, int *index, int *arity);

Decodes a tuple header, and the number of elements comes back in arity. The tuple elements follow in order in the buffer.

ei_decode_ulong()

int ei_decode_ulong(const char *buf, int *index, unsigned long *p);

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

ei_decode_ulonglong()

int ei_decode_ulonglong(const char *buf, int *index, unsigned long long *p);

Decodes a GCC unsigned long long or Visual C++ unsigned __int64 (64-bit) integer from the binary format.

ei_decode_version()

int ei_decode_version(const char *buf, int *index, int *version);

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


ei_encode_atom()

ei_encode_atom_len()

ei_x_encode_atom()

ei_x_encode_atom_len()

int ei_encode_atom(char *buf, int *index, const char *p);

int ei_encode_atom_len(char *buf, int *index, const char *p, int len);

int ei_x_encode_atom(ei_x_buff* x, const char *p);

int ei_x_encode_atom_len(ei_x_buff* x, const char *p, int len);

Encodes an atom in the binary format. The 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.

ei_encode_atom_as()

Available since OTP R16B

ei_encode_atom_len_as()

Available since OTP R16B

ei_x_encode_atom_as()

Available since OTP R16B

ei_x_encode_atom_len_as()

int ei_encode_atom_as(char *buf, int *index, const char *p,
  erlang_char_encoding from_enc, erlang_char_encoding to_enc);

int ei_encode_atom_len_as(char *buf, int *index, const char *p, int len,
  erlang_char_encoding from_enc, erlang_char_encoding to_enc);

int ei_x_encode_atom_as(ei_x_buff* x, const char *p,
  erlang_char_encoding from_enc, erlang_char_encoding to_enc);

int ei_x_encode_atom_len_as(ei_x_buff* x, const char *p, int len,
  erlang_char_encoding from_enc, erlang_char_encoding to_enc);

Encodes an atom in the binary format. The 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 you gotta use a function variant with a len parameter.

The encoding fails if p is not a valid string in encoding from_enc. πŸ’€

The to_enc argument is ignored. As of Erlang/OTP 20 the encoding is always done in UTF-8, which is readable by nodes as old as Erlang/OTP R16. 🌈

Available since OTP R16B

ei_encode_bignum()

ei_x_encode_bignum()

int ei_encode_bignum(char *buf, int *index, mpz_t obj);

int ei_x_encode_bignum(ei_x_buff *x, mpz_t obj);

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.

ei_encode_binary()

ei_x_encode_binary()

int ei_encode_binary(char *buf, int *index, const void *p, long len);

int ei_x_encode_binary(ei_x_buff* x, const void *p, long len);

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

ei_encode_bitstring()

Available since OTP 22.0

ei_x_encode_bitstring()

int ei_encode_bitstring(char *buf, int *index, const char *p, size_t bitoffs, size_t nbits);

int ei_x_encode_bitstring(ei_x_buff* x, const char *p, size_t bitoffs, size_t nbits);

Encodes a bit string in the binary format.

The data is at p. The length of the bit string is nbits bits. The first bitoffs bits of the data at p are unused. The first byte which is part of the bit string is p[bitoffs/8]. The bitoffs%8 most significant bits of the first byte p[bitoffs/8] are unused.

The number of bytes which is part of the bit string is (bitoffs + nbits + 7)/8. If (bitoffs + nbits)%8 > 0 then only (bitoffs + nbits)%8 bits of the last byte are used. Unused bits in the last byte are the least significant bits.

The values of unused bits are disregarded and don't need to be cleared. 🧹

Available since OTP 22.0

ei_encode_boolean()

ei_x_encode_boolean()

int ei_encode_boolean(char *buf, int *index, int p);

int ei_x_encode_boolean(ei_x_buff* x, int p);

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

ei_encode_char()

ei_x_encode_char()

int ei_encode_char(char *buf, int *index, char p);

int ei_x_encode_char(ei_x_buff* x, char p);

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. 🫠

ei_encode_double()

ei_x_encode_double()

int ei_encode_double(char *buf, int *index, double p);

int ei_x_encode_double(ei_x_buff* x, double p);

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

Returns -1 if the floating point number is not finite. πŸ’€

ei_encode_empty_list()

ei_x_encode_empty_list()

int ei_encode_empty_list(char* buf, int* index);

int ei_x_encode_empty_list(ei_x_buff* x);

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

ei_encode_fun()

ei_x_encode_fun()

int ei_encode_fun(char *buf, int *index, const erlang_fun *p);

int ei_x_encode_fun(ei_x_buff* x, const erlang_fun* fun);

Encodes a fun in the binary format. The parameter p points to an erlang_fun structure. The erlang_fun is not freed automatically β€” free_fun is to be called if the fun is not needed after encoding. πŸŽ€

ei_encode_list_header()

ei_x_encode_list_header()

int ei_encode_list_header(char *buf, int *index, int arity);

int ei_x_encode_list_header(ei_x_buff* x, int arity);

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 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);
πŸ’‘ NOTE: It may seem like there's no way to create a list without knowing the number of elements in advance. But bestie, 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);

ei_encode_long()

ei_x_encode_long()

int ei_encode_long(char *buf, int *index, long p);
int ei_x_encode_long(ei_x_buff* x, long p);

Encodes a long integer in the binary format β€” yes bestie, the whole binary format thing, that's the entire job description. And heads up: if your code is 64 bits, ei_encode_long() is literally the same function as ei_encode_longlong(). Same girl, different name tag. πŸ’…


πŸ¦‹ ei_encode_longlong() / ei_x_encode_longlong() πŸ¦‹

int ei_encode_longlong(char *buf, int *index, long long p);

int ei_x_encode_longlong(ei_x_buff* x, long long p);

Encodes a GCC long long or Visual C++ __int64 β€” that's a 64-bit integer, ikyk β€” in the binary format. Big number energy only. πŸ”₯

πŸŽ€ ei_encode_map_header() / ei_x_encode_map_header() πŸŽ€

Available since OTP 17.0
int ei_encode_map_header(char *buf, int *index, int arity);

int ei_x_encode_map_header(ei_x_buff* x, int arity);

Encodes a map header, with a specified arity. The next arity*2 terms you encode will be the keys and values of the map, and they go in this exact order: K1, V1, K2, V2, ..., Kn, Vn. Keys and values, keys and values, alternating like a friendship bracelet. 🫢

So say you wanna encode the map #{a => "Apple", b => "Banana"} β€” here's the whole ritual:

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. That's not a vibe, that's a rule. Duplicate keys = invalid map, periodt.
Available since OTP 17.0

🌸 ei_encode_pid() / ei_x_encode_pid() 🌸

int ei_encode_pid(char *buf, int *index, const erlang_pid *p);

int ei_x_encode_pid(ei_x_buff* x, const erlang_pid *p);

Encodes an Erlang process identifier (a pid) in the binary format. The parameter p points to an erlang_pid structure, and that struct should either have been obtained earlier with ei_decode_pid(), ei_self(), or freshly created by ei_make_pid(). No making up pids out of thin air, bestie. 😭

🌈 ei_encode_port() / ei_x_encode_port() 🌈

int ei_encode_port(char *buf, int *index, const erlang_port *p);

int ei_x_encode_port(ei_x_buff* x, const erlang_port *p);

Encodes an Erlang port in the binary format. Parameter p points to an erlang_port structure which should have been obtained earlier with ei_decode_port(), β€” yes that's the original punctuation, a comma, I'm not fixing it, I'm not that kind of girl. πŸ™ˆ

πŸ“ ei_encode_ref() / ei_x_encode_ref() πŸ“

int ei_encode_ref(char *buf, int *index, const erlang_ref *p);

int ei_x_encode_ref(ei_x_buff* x, const erlang_ref *p);

Encodes an Erlang reference in the binary format. Parameter p points to an erlang_ref structure which either should have been obtained earlier with ei_decode_ref(), or created by ei_make_ref(). Two valid origin stories, pick one. ✨

πŸ’œ ei_encode_string() / ei_encode_string_len() / ei_x_encode_string() / ei_x_encode_string_len() πŸ’œ

int ei_encode_string(char *buf, int *index, const char *p);

int ei_encode_string_len(char *buf, int *index, const char *p, int len);

int ei_x_encode_string(ei_x_buff* x, const char *p);

int ei_x_encode_string_len(ei_x_buff* x, const char* s, int len);

Encodes a string in the binary format. And here's the plot twist that gets everybody: a string in Erlang is a list, but it gets encoded as a character array in the binary format. Not a list. A char array. The lore is deep. 🌊

The string is supposed to be NULL-terminated β€” except for ei_x_encode_string_len(), which is the one girl with a len and doesn't need the null. She knows how long she is. πŸ’…

🧚 ei_encode_trace() / ei_x_encode_trace() 🧚

int ei_encode_trace(char *buf, int *index, const erlang_trace *p);

int ei_x_encode_trace(ei_x_buff* x, const erlang_trace *p);

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(). Following the trace, fr fr. πŸ”

πŸ‘‘ ei_encode_tuple_header() / ei_x_encode_tuple_header() πŸ‘‘

int ei_encode_tuple_header(char *buf, int *index, int arity);

int ei_x_encode_tuple_header(ei_x_buff* x, int arity);

Encodes a tuple header, with a specified arity. The next arity terms you encode are the elements of the tuple. And the way that tuples and lists are encoded recursively means a tuple can absolutely contain another tuple or a list β€” nesting doll situation, we love to see it. πŸͺ†

Case in point: 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);

See that last one? 0 arity, an empty tuple, iconic behaviour honestly. πŸ’–

⭐ ei_encode_ulong() / ei_x_encode_ulong() ⭐

int ei_encode_ulong(char *buf, int *index, unsigned long p);

int ei_x_encode_ulong(ei_x_buff* x, unsigned long p);

Encodes an unsigned long integer in the binary format. And same as before: if the code is 64 bits, ei_encode_ulong() is the same as ei_encode_ulonglong(). No negativity allowed over here. πŸ™…

🌟 ei_encode_ulonglong() / ei_x_encode_ulonglong() 🌟

int ei_encode_ulonglong(char *buf, int *index, unsigned long long p);

int ei_x_encode_ulonglong(ei_x_buff* x, unsigned long long p);

Encodes a GCC unsigned long long or Visual C++ unsigned __int64 β€” the 64-bit unsigned situation β€” in the binary format.

πŸŽ€ ei_encode_version() / ei_x_encode_version() πŸŽ€

int ei_encode_version(char *buf, int *index);

int ei_x_encode_version(ei_x_buff* x);

Encodes a version magic number for the binary format. Must be the first token in a binary term. First. Like, before anything else. She's the opening act or there's no show. 🎀


πŸ”₯ ei_get_type() πŸ”₯

int ei_get_type(const char *buf, const int *index, int *type, int *size);

Returns the type in *type and the size in *size of the encoded term. And because obviously you're wondering what "size" even means here, let me break it down, bestie:

  • For strings and atoms, size is the number of characters, not including the terminating NULL.
  • For binaries and bitstrings, *size is the number of bytes.
  • For lists, tuples and maps, *size is the arity of the object.
  • For bignum integers, *size is the number of bytes for the absolute value of the bignum.
  • For other types, *size is 0.

In all cases, index is left unchanged. She doesn't touch your index. Respectful queen. πŸ‘‘

Currently *type is one of these:

  • ERL_ATOM_EXT β€” decode using either ei_decode_atom(), ei_decode_atom_as(), or ei_decode_boolean().
  • ERL_BINARY_EXT β€” decode using either ei_decode_binary(), ei_decode_bitstring(), or ei_decode_iodata().
  • ERL_BIT_BINARY_EXT β€” decode using ei_decode_bitstring().
  • ERL_FLOAT_EXT β€” decode using ei_decode_double().
  • ERL_NEW_FUN_EXT, ERL_FUN_EXT, ERL_EXPORT_EXT β€” decode using ei_decode_fun().
  • ERL_SMALL_INTEGER_EXT, ERL_INTEGER_EXT, ERL_SMALL_BIG_EXT, ERL_LARGE_BIG_EXT β€” decode using either ei_decode_char(), ei_decode_long(), ei_decode_longlong(), ei_decode_ulong(), ei_decode_ulonglong(), or ei_decode_bignum().
  • ERL_LIST_EXT, ERL_NIL_EXT β€” decode using either ei_decode_list_header(), or ei_decode_iodata().
  • ERL_STRING_EXT β€” decode using either ei_decode_string(), or ei_decode_iodata().
  • ERL_MAP_EXT β€” decode using ei_decode_map_header().
  • ERL_PID_EXT β€” decode using ei_decode_pid().
  • ERL_PORT_EXT β€” decode using ei_decode_port().
  • ERL_NEW_REFERENCE_EXT β€” decode using ei_decode_ref().
  • ERL_SMALL_TUPLE_EXT, ERL_LARGE_TUPLE_EXT β€” decode using ei_decode_tuple_header().

And ngl, if you're not even interested in the data? You can also just skip past the term entirely by using ei_skip_term(). Not every term deserves your attention, and that's valid. πŸ’…


🌸 ei_init() 🌸

int ei_init(void);

Initializes the ei library. This function should be called once β€” and only once β€” before you call any other functionality in the ei library. One time. That's it. Not a "just to be safe" situation. 😭

On success, zero is returned. On failure, a posix error code is returned.

Available since OTP 21.3

πŸ’– ei_print_term() / ei_s_print_term() πŸ’–

int ei_print_term(FILE* fp, const char* buf, int* index);

int ei_s_print_term(char** s, const char* buf, int* index);

Prints a term, in clear text, to the file specified by fp, or to the buffer pointed to by s. It genuinely tries to resemble the term printing you get in the Erlang shell β€” so the vibes are familiar. 🐚

With ei_s_print_term(), the parameter s is meant to point to a dynamically (malloc) allocated string of BUFSIZ bytes, or to a NULL pointer. And plot twist: the string can get reallocated β€” and *s can be updated β€” by this function if the result ends up being more than BUFSIZ characters. She grows when she needs to. 🌱 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. And unfortunately, I/O errors on fp are not checked. Not checked!! Like, at all. 🫠

Argument index is updated, so basically you can view this function as a decode function that decodes a term into a human-readable format. Decoding, but make it cozy.


πŸ’€ ei_set_compat_rel() πŸ’€

void ei_set_compat_rel(unsigned release_number);

Okay so generally speaking, the ei library is guaranteed to be compatible with other Erlang/OTP components that are 2 major releases older or newer than the ei library itself. That's the promise. That's the deal.

But sometimes an exception to that rule has to be made, so that new features β€” or even just bug fixes β€” are possible. And a call to ei_set_compat_rel(release_number) sets the ei library into compatibility mode for the OTP release release_number.

The only useful value for release_number is currently 21. And this will only be useful and have an effect if bit strings or export funs are received from a connected node. Before OTP 22, bit strings and export funs were not supported by ei β€” instead they were encoded using an undocumented fallback tuple format when sent from the emulator to ei. Undocumented. Fallback. Tuple. Format. The drama. 🎭

  • Bit string β€” the term <<42, 1:1>> was encoded as {<<42, 128>>, 1}. The first element of the tuple is a binary, and the second element denotes how many bits of the last bytes are part of the bit string. In this example, only the most significant bit of the last byte (128) is part of the bit string.
  • Export fun β€” the term fun lists:map/2 was encoded as {lists,map}. A tuple with the module, the function, and a missing arity.

If ei_set_compat_rel(21) is not called, then a connected emulator will send bit strings and export funs correctly encoded. In that case, ei_decode_bitstring and ei_decode_fun have to be used to decode such terms. And listen: calling ei_set_compat_rel(21) should only be done as a workaround to keep an old implementation alive β€” one that expects to receive the undocumented tuple formats for bit strings and/or export funs. Workaround only. Not a lifestyle. 🚩

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

πŸ¦‹ ei_skip_term() πŸ¦‹

int ei_skip_term(const char* buf, int* index);

Skips a term in the specified buffer β€” and it recursively skips elements of lists and tuples, so that a full term is skipped. All of it. The whole thing. This is also a way to get the size of an Erlang term, which is lowkey so useful.

buf is the buffer.

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

NOTE: 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.


πŸŽ€ ei_x_append() / ei_x_append_buf() πŸŽ€

int ei_x_append(ei_x_buff* x, const ei_x_buff* x2);

int ei_x_append_buf(ei_x_buff* x, const char* buf, int len);

Appends data at the end of buffer x. Short and sweet, she does one thing and she does it flawlessly. πŸ’…


✨ ei_x_format() / ei_x_format_wo_ver() ✨

int ei_x_format(ei_x_buff* x, const char* fmt, ...);

int ei_x_format_wo_ver(ei_x_buff* x, const char *fmt, ... );

Formats a term, given as a string, to a buffer. Think of it as sprintf but for Erlang terms β€” same energy, different universe. 🌈 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 β€” an unsigned long integer, unsigned long int
  • ~f β€” a float, float
  • ~d β€” a double float, double float
  • ~p β€” an Erlang pid, erlang_pid*

okay so say you wanna encode a tuple with some stuff in it, right? like:

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

that encodes the tuple {numbers,12,3.14159} πŸ’« literally that easy bestie.

ei_x_format_wo_ver() formats into a buffer, but without the initial version byte. so like, no version header, none, zero, nada. πŸ™ˆ

CHANGE: since OTP 26.2, maps can be encoded with syntax like "#{k1 => v1, k2 => v2}". slay! πŸ—ΊοΈβœ¨

πŸ’… ei_x_free()

int ei_x_free(ei_x_buff* x);

Deallocates the dynamically allocated content of the buffer that x is pointing at. And bestie, after the deallocation happens, the buff field gets set to NULL. clean. 🧼

πŸŽ€ ei_x_new() / ei_x_new_with_version()

int ei_x_new(ei_x_buff* x);
int ei_x_new_with_version(ei_x_buff* x);

These initialize the dynamically realizable buffer that x refers to. The fields of the structure pointed to by parameter x get filled in, and a default buffer is allocated. ✨

And ei_x_new_with_version()? she's extra in the best way β€” she also puts an initial version byte, which is the one used in the binary format (so that ei_x_encode_version() will not be needed). periodt. πŸ’… no extra call required, we love a self-sufficient queen.

πŸ› Debug Information πŸ›

some tips on what to check when the emulator does not seem to receive the terms 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. πŸ‘€

and that's a wrap babe!! πŸŽ¬πŸ’– this lil masterpiece came to you courtesy of Ericsson AB, running erl_interface version 5.8.2, filed under section 3 of the ei manual β€” go forth and encode ur tuples, you're doing amazing sweetie πŸŒˆπŸ‘‘πŸ’œ

πŸ“¦ where this page comes from