nlohmann / fifo_map

a FIFO-ordered associative container for C++
MIT License
179 stars 77 forks source link

Persist fifo counter at copy #5

Closed dkourilov closed 6 years ago

dkourilov commented 6 years ago

This PR fixes a bug when nlohmann::basic_json<fifo_map>::merge_patch is used after copying of a nlohmann::basic_json<fifo_map> object.

Without copying of a timestamp counter, nested fields will be overwritten at their timestamp positions instead of names during merge_patch. Possibly other functionality will be broken too, but we have discovered problem particularly when were using merge_patch.

Minimal example to reproduce the problem with current master:

#include <nlohmann/fifo_map.hpp>
#include <nlohmann/json.hpp>
#include <iostream>

template<class K, class V, class C, class A>
using fifo_map = nlohmann::fifo_map<K, V, nlohmann::fifo_map_compare<K>, A>;
using json = nlohmann::basic_json<fifo_map>;

static const json base_json =
{
    {"field1", {
        {"field11", {
            {"field111", {
                {"field1111", {
                    {"field11111", "value"}
                }}
            }}
        }},
        {"field21", {
            {"field211", {
                {"field2111", {
                    {"field21111", "value"}
                }}
            }}
        }}
    }}
};

int main(int argc, char *argv[])
{
    json schema = base_json; // timestamp is reset here during copying

    schema.merge_patch(
    {
        {"field1", {
            {"field13", {"value3"}},
            {"field14", "value4"}
        }}
    });

    std::cout << schema.dump(4) << std::endl;

    return 0;
}

Output with master:

{
    "field1": {
        "field11": [
            "value3"
        ],
        "field21": "value4"
    }
}

Expected output:

{
    "field1": {
        "field11": {
            "field111": {
                "field1111": {
                    "field11111": "value"
                }
            }
        },
        "field21": {
            "field211": {
                "field2111": {
                    "field21111": "value"
                }
            }
        },
        "field13": [
            "value3"
        ],
        "field14": "value4"
    }
}
nlohmann commented 6 years ago

Thanks for being so patient!