Skip to content
Marc edited this page Aug 14, 2018 · 17 revisions

Fields are the simplest serialized data object. It has a name, and stores a single data type. The valid data types are: bool, char, byte, short, int, long long, float, double and std::string
They are a good choice if you only need to store the contents of a single variable.

Using fields

To use fields, you only need to include Cereal.h.
Now, type the following in your code:

Cereal::Field* myField = new Cereal::Field("Field name", 'A');

That will create a field with the name "Field name" and will store the character A. Now, you can use the function Field::write(Buffer& buffer) to serialize its contents to a buffer:

myField->write(buffer); // Write the contents of a field to the buffer

If the writing process fails, the function write will return false. Else, it will return true. Normally, if the writing process has failed, it means the buffer is too small to store this field.

Instead, if you need to deserialize the contents of a field, you will have to read a buffer containing a field, and then call Field::getValue<dataType>():

Cereal::Field* myField = new Cereal::Field; // We create an empty field because we will overwrite it anyway
myField->read(buffer); // Now the field is full of data
char deserializedData = myField->getValue<char>(); // We store the contents of the field

For more information about how to use fields with objects, check out objects.

Other methods

You might want to retrieve the field name. For such operation, just call Field::getName():

std::string fieldName = myField->getName();

If you want to know how many bytes your field is using, call Field::getSize(). It returns an unsigned int with the byte count for this particular field.
Finally, if you want to know what kind of data your field is storing, call Field::getDataType() like so:

DataType type = myField->getDataType();

if(type == DataType::DATA_INT)
{
    // Do something if the data contained is an int
    // ...
}

Sample code

#include <Cereal.h> // Include the library

int main()
{
    Cereal::Buffer buffer(1024); // Create a buffer with 1024 bytes
    Cereal::Field* myField = new Cereal::Field("Field name", 'A');

    // Writing a field
    myField->write(buffer); // Write the field to the buffer

    // Reading a field
    Cereal::Field* otherField = new Cereal::Field; // Create another field
    buffer.setOffset(0); // Move the buffer back to the beginning
    otherField->read(buffer); // Read the field from the buffer
    char data = otherField->getValue<char>(); // Now data should be equal to 'A'

    // Free dynamic memory
    delete myField;
    delete otherField;

    return 0;
}