Function sample_global_allocator


#include <samples/quickstart.cpp>

void sample_global_allocator()


set a global allocator for ryml

demonstrates how to set the global allocator for ryml

Mentioned in


Lines 3555-3607 in samples/quickstart.cpp. Line 74 in samples/quickstart.cpp.

void sample_global_allocator()
    GlobalAllocatorExample mem;

    // save the existing callbacks for restoring
    ryml::Callbacks defaults = ryml::get_callbacks();

    // set to our callbacks

    // verify that the allocator is in effect
    ryml::Callbacks const& current = ryml::get_callbacks();
    CHECK(current.m_allocate == &mem.s_allocate);
    CHECK(current.m_free == &mem.s_free);

    // so far nothing was allocated
    CHECK(mem.alloc_size == 0);

    // parse one tree and check
    (void)ryml::parse(R"({foo: bar})");

    // parse another tree and check
    (void)ryml::parse(R"([a, b, c, d, {foo: bar, money: pennys}])");

    // verify that by reserving we save allocations
        ryml::Parser parser;      // reuse a parser
        ryml::Tree tree;          // reuse a tree

        tree.reserve(10);         // reserve the number of nodes
        tree.reserve_arena(100);  // reserve the arena size
        parser.reserve_stack(10); // reserve the parser depth.

        // since the parser stack uses Small Storage Optimization,
        // allocations will only happen with capacities higher than 16.
        CHECK(mem.num_allocs == 2); // tree, tree_arena and NOT the parser

        parser.reserve_stack(20); // reserve the parser depth.
        CHECK(mem.num_allocs == 3); // tree, tree_arena and now the parser as well

        // verify that no other allocations occur when parsing
        size_t size_before = mem.alloc_size;
        parser.parse("", R"([a, b, c, d, {foo: bar, money: pennys}])", &tree);
        CHECK(mem.alloc_size == size_before);
        CHECK(mem.num_allocs == 3);

    // restore defaults.

Add Discussion as Guest

Log in