goertzenator / nifpp

C++11 Wrapper for Erlang NIF API
125 stars 61 forks source link

Support generating map of maps #15

Open vasu-dasari opened 3 years ago

vasu-dasari commented 3 years ago

Add API to be able to add entries to map. And modify existing map's make() API to be able to accept an existing map to add to.

Added a new testcase nestedmap_test to demonstrate this.

Signed-off-by: Vasu Dasari vdasari@gmail.com

goertzenator commented 3 years ago

Thank you for your contribution, and especially for also adding tests!

I'd like to push back on the make() implementations that you tweaked; they seem inessential as you can just write a loop with add_to_map(), and they break the assumption of what "make" means in my mind (one c++ object gets converted to one new term). If you take that out I will merge this immediately, but you are welcome to trying changing my mind if these "make" tweaks are important to you. ;)

vasu-dasari commented 3 years ago

Thanks. I see your point. Extending make() the way it is in PR would give ability to merge another map into current one as well. As you can see I have extended the make() by using "default arguments", so practically none of the API users code should get disturbed. If you still prefer that make() should be left alone, we can introduce another API merge(). Let me know what you think.

// Build a nested map
nifpp::TERM nestedmap_test(ErlNifEnv* env, ERL_NIF_TERM )
{
    std::map<nifpp::str_atom, int> int_map = {
        {"a", 1}
    };
    nifpp::TERM outmap = make(env, int_map);

    // Add another entry to map
    add_to_map(env, std::make_pair(str_atom("b"), "b"), outmap);

    // Add a nested map
    std::map<nifpp::str_atom, int> nested_map = {
        {"a1" , 1},
        {"b1" , 2}
    };
    add_to_map(env, std::make_pair(str_atom("c"), make(env, nested_map)), outmap);

    // Merge another map into outmap
    std::map<nifpp::str_atom, std::string> str_map = {
        {"x", "1"},
        {"y", "2"}
    };
    outmap = make(env, str_map, &outmap);

    return outmap;
}