Skip to content

Basic Containers

Vinícius Garcia edited this page May 2, 2017 · 11 revisions

packToken: The default container for all tokens

The packToken is a C++ class designed to unify all the token access functions.

It can be used to keep different values:

packToken p1 = 10;
packToken p2 = "string";
packToken p3 = TokenMap();

And it helps you to work with different types of tokens:

// Find out its type:
uint8_t p1_type = p1->type; // INT type.

// Serialize it:
std::string str = p1.str(); // "10"
std::cout << p3 << std::endl; // "{}" (an empty map)

// Or even cast it between different compatible types:
double p1_asDouble = p1.asDouble();
int p1_asInt = p1.asInt();

// If the cast is invalid, it throws an error:
std::string p1_asString = p1.asString();

Note that if your goal is to serialize a token p1.str() is the correct way to do it, since asString() is a cast and would throw an error for tokens that are not strings.

TokenMap: The key-value container of packTokens

The TokenMap container is a very versatile object with an intuitive API:

You can create an empty map.

TokenMap M;

Add stuff to it as you like:

M["my_int"] = 10;
M["my_string"] = "text";

Even add other maps or lists:

TokenMap M1;
M["my_map"] = M1;
M["my_list"] = TokenList();

Accessing maps inside of maps is also intuitive:

M["my_map"]["who"] = "this is the map M1";

std::cout << M1["who"] << std::endl; // "this is the map M1"

TokenList: The serial container of packTokens

The TokenList is implemented as an std::vector<packToken> thus optimized for random access read and writes.

To build a list just push each element into it:

TokenList L;

L.push("my value");
L.push(10);
L.push(TokenMap());
L.push(TokenList());

std::cout << packToken(L) << std::endl;  // [ "my value", 10, {}, [] ]

Remove elements with the pop() function (always from the back of the list):

std::cout << L.pop() << std::endl;  // []
std::cout << L.pop() << std::endl;  // {}
std::cout << packToken(L) << std::endl;  // [ "my value", 10 ]

Access items by index:

std::cout << L[0] << std::endl; // "my string"
std::cout << L[1] << std::endl; // 10
std::cout << L[1000] << std::endl; // throw an std::out_of_range exception

Also note that you can access the internal std::vector using the TokenList::list() getter:

std::cout << L.list()[0] << std::endl; // "my string"
std::cout << L.list()[1] << std::endl; // 10
std::cout << L.list()[2] << std::endl; // {}
std::cout << L.list()[3] << std::endl; // []

It is a little bit faster but does not protect you from accessing invalid positions.

Clone this wiki locally