RejectedSoftware Forums

Sign up

Json parser lifetime question

If I have a string that is heap allocated:

auto jsonString = `{"a": "b",`;
jsonString ~= `"c": 1}`;

Now, if I parse this using vibe.data.json into a Json object, what
happens if I delete the jsonString? Will this destroy the memory used by
the Json object? I'm assuming so, but I wanted to understand if Json is
already doing this or not.

-Steve

Re: Json parser lifetime question

On Thu, 11 Aug 2016 18:15:29 -0400, Steven Schveighoffer wrote:

If I have a string that is heap allocated:

auto jsonString = `{"a": "b",`;
jsonString ~= `"c": 1}`;

Now, if I parse this using vibe.data.json into a Json object, what
happens if I delete the jsonString? Will this destroy the memory used by
the Json object? I'm assuming so, but I wanted to understand if Json is
already doing this or not.

-Steve

The Json struct is stored similar to an Algebraic!(bool, int, string, Json[], Json[string]) (in contrast to Bson, which parses the original source data on demand). So any string constants will be destroyed (object keys or string values), but the structure of arrays and objects will remain allocated.

Deleting the rest should work manually:

void del(Json json) {
    if (json.type == Json.Type.array) {
        foreach (e; json) del(e);
        delete json.get!(Json[]);
    } else if (json.type == Json.Type.object) {
        foreach (e; json) del(e);
        delete json.get!(Json[string]);
    }
}

Re: Json parser lifetime question

On 8/14/16 8:52 AM, Sönke Ludwig wrote:

The Json struct is stored similar to an Algebraic!(bool, int, string, Json[], Json[string]) (in contrast to Bson, which parses the original source data on demand). So any string constants will be destroyed (object keys or string values), but the structure of arrays and objects will remain allocated.

OK. I'm dealing with mysql-native, which instead of allocating strings
on the heap just casts from the input stream. So there are lifetime
issues there. I'll just idup before I give it to the json parser.

Thanks

-Steve