3 ms·
If this is at all like jq's libjq's jv API [0], then this it will be great. The C-coded jv API gives you immutable JSON-ish data structures, with the illusion
by cryptonector 9y ago
If this is at all like jq's libjq's jv API [0], then this it will be great. The C-coded jv API gives you immutable JSON-ish data structures, with the illusion (and sometimes truth) that they are actually mutable.
For example, say you have
jv foo(jv a)
{
return jv_array_append(a, jv_string("foo"));
}
Here `jv_array_append()` looks like it must mutate `a`. What actually happens under the covers is that if `a` has just one reference, then indeed, `a` will be mutated, but if it has more than one reference then a new array will be constructed as a copy of `a`, `a`'s reference count will be decremented, the copy will be mutated, and lastly the copy will be returned.
This might make it a bit clearer:
jv a = jv_array();
a = jv_array_append(a, jv_true());
a = jv_array_append(a, jv_false());
a = jv_array_append(a, jv_null());
Each assignment to `a` here can be a brand new array, though since in this code snippet `a` will always have just one reference, in fact `a` will always be mutated.
Now, look at this:
jv a = JV_ARRAY(jv_true(), jv_false(), jv_null());
set_thingy(jv_copy(a));
a = jv_array_append(a, jv_number(10));
here at the third line `a` might have two references, depending on what `set_thingy()` might have done with its reference. Perhaps `set_thingy()` saved its reference in a global or thread-local variable, or some object reachable from a global or thread-local variable, in which case the last call to `jv_array_append()` in this example will produce a brand new array.
See the jq jv wiki[1].
Now, this is all C. But in Rust all of this would be even more powerful.
[0] https://github.com/stedolan/jq/blob/master/src/jv.h https://github.com/stedolan/jq/blob/master/src/jv.h
[1] https://github.com/stedolan/jq/wiki/C-API:-jv https://github.com/stedolan/jq/wiki/C-API:-jv