Skip to content
Marc edited this page Jun 27, 2018 · 4 revisions

Headers are completely optional, but they are a good solution if you need to store more than one database in a single file.

Headers don't have a name, they just store the databases (up to 255 of them).

Using headers

To use headers, you have to include the file Cereal.h. Once this is done, you can create your header:

Cereal::Header* header = new Cereal::Header;

Now, to add databases to the header, use the function Header::add(Database* database):

header->add(database);

To write the header and all its databases to a buffer, just call Header::write(Buffer& buffer), like so:

header->write(myBuffer);

Finally, to read a header and all the databases it contains, you have to execute Header::read(Buffer& buffer):

header->read(myBuffer);

Sample code

#include <Cereal.h>

int main()
{
    Cereal::Database* db = new Cereal::Database("Database name");
    // TODO: Add objects to the database

    Cereal::Buffer buffer(1024); // Create a buffer with 1024 bytes
    Cereal::Header* header = new Cereal::Header; // We create our header
    
    // Adding databases to a header
    header->addDatabase(db);

    // Writing the header to a buffer
    header->write(buffer);

    // Reading a header and its databases
    Cereal::Header* otherHeader = new Cereal::Header;
    buffer.setOffset(0); // Move the buffer back to the begining
    otherHeader->read(buffer); // Read the header and the databases

    // Getting a database from a header
    Cereal::Database* myDatabase = header->getDatabase("Database name");

    // Free dynamic memory
    delete header;
    delete otherHeader;

    return 0;
}