问题
I have a nested list of the form,
{stack, "over", flow, ["is", "a"], ["knowledge", "sharing", "site"], "a", "b"}
I am not able to cleanly decode the above tuple. I decode the above into a
vector<vector<string> >
However, If I replace the inner lists into a tuple, I am able to decode that fine. I doubt that the usage of ERL_NIL_EXT and ERL_LIST_EXT but the documentation is only a little helpful.
Idea is if I get list inside my tuple, I am decoding that and returning a vector of strings and do walk the tuple linearly. But I am not sure whats wrong. Help!
Code:
vector< vector<string> > decode_tuple(char *buff)
{
vector< vector<string> > decoded_tuple;
int index = 0;
int size;
int res = ei_decode_tuple_header(buff, &index, &size);
for(int i = 0; i < size; ++i)
{
int entry_size;
int type;
int res = ei_get_type(buff, &index, &type, &entry_size);
char *decoded_val = (char *) malloc(sizeof(char) * (entry_size + 1));
switch (type)
{
case ERL_ATOM_EXT:
{
vector<string> value;
ei_decode_atom(buff, &index, decoded_val);
cout<<decoded_val<<endl;
value.push_back(decoded_val);
decoded_tuple.push_back(value);
free(decoded_val);
break;
}
case ERL_STRING_EXT:
{
vector<string> value;
ei_decode_string(buff, &index, decoded_val);
cout<<decoded_val<<endl;
value.push_back(decoded_val);
decoded_tuple.push_back(value);
free(decoded_val);
break;
}
case ERL_SMALL_TUPLE_EXT:
case ERL_LARGE_TUPLE_EXT:
{
pair<int, vector<string> > value;
value = decode_inner_tuple(buff, index);
index = value.first;
decoded_tuple.push_back(value.second);
break;
}
case ERL_NIL_EXT:
{
vector<string> value;
ei_decode_string(buff, &index, decoded_val);
free(decoded_val);
break;
}
case ERL_LIST_EXT:
{
pair<int, vector<string> > value;
value = decode_inner_list(buff, index);
index = value.first;
decoded_tuple.push_back(value.second);
break;
}
default:
cout<<"Not a valid string"<<endl;
break;
}
}
return decoded_tuple;
}
pair<int, vector<string> > decode_inner_list(char *buff, int index)
{
vector<string> decoded_list;
int size;
int res = ei_decode_list_header(buff, &index, &size);
for(int i = 0; i < size; ++i)
{
int entry_size;
int type;
int res = ei_get_type(buff, &index, &type, &entry_size);
if(type == ERL_STRING_EXT)
{
char *decoded_value = (char *)malloc(sizeof(char) * (entry_size + 1));
ei_decode_string(buff, &index, decoded_value);
decoded_list.push_back(decoded_value);
free(decoded_value);
}
else
{
cout << "Not a valid string" << endl;
break;
}
}
return make_pair(index, decoded_list);
};
回答1:
The problem is with how you handle ERL_NIL_EXT. That type represents an empty list, which means it's composed of just a list header with no elements. To decode it, just decode a list header:
case ERL_NIL_EXT:
ei_decode_list_header(buff, &index, &entry_size);
break;
来源:https://stackoverflow.com/questions/36817203/using-ei-decode-list-when-decoding-a-nested-list-of-elements