[erlang-questions] ei_decode ???

Romain Lenglet <>
Wed Oct 4 07:47:42 CEST 2006


Sanjaya Vitharana wrote:
> Consider a List [A,B] where A,B=ANY integer (including 0..255)
>
> So how to decode it using ei_decode functions??

In that case, if the list contains only integers in [0..255], and 
if the list is flat, it will always be encoded as a string.
Otherwise, it will be encoded as a list of integers.

> Reason:
> (condsidering ei_get_type(buf, &index, &type, &size))
> 1.) [A,B] where ANY of A,B > 255 so [A,B] = List
> (ei_decode_list_header(...) works fine here) 2.) [A,B] where
> A,B <= 255 so [A,B] = String (in this case how to use
> ei_decode_string(...) to decode the values of A,B ??)
>
> of course I can use tuple to do this quickly. But like to know
> how to decode 2.) for my general knowledge

Here is a general and efficient algorithm for decoding a list of 
integers, simplified from actual code from Dryverl:

void foo(char *buffer, int *index) {

int is_string = 0;
char *string_buffer = NULL;
int size = 0;
unsigned long val = 0L;
int i = 0;

ei_get_type(buffer, index, &is_string, &size);
if (is_string = (is_string == ERL_STRING_EXT)) {
    /* Skip the string type and length. */
    *index += 1 + 2;
} else {
    /* Skip the list type and length. */
    ei_decode_list_header(buffer, index, NULL);
}

/* Decode and display every integer in the list. */
for (i = 0; i < size; i++) {
    if (is_string) {
        val = ((unsigned char*)buffer)[(*index)++];
    } else {
        ei_decode_ulong(buffer, index, &val);
    }
    printf("%lu\r\n", val);
}

/* Decode the tail of the list, if it was not empty.
  We assume that the list is flat,
  i.e. the tail is [], which encoded as one byte. */
if ((!is_string) && (size > 0)) *index++;
/* Or, more conventionally:
if ((!is_string) && (size > 0))
    ei_decode_list_header(buffer, index, NULL);
*/

}


You have to add error handling everywhere. I omitted it here for 
clarity.

An undocumented function of ei is ei_decode_intlist.
But my version above is more efficient, because it does no copy 
of data into a new array.

Regards,

-- 
Romain LENGLET
Pr. Chiba Shigeru Group
Dept. of Mathematical and Computing Sciences
Tokyo Institute of Technology



More information about the erlang-questions mailing list