X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=lib%2Fsmap.c;h=0d757330552fd1b6758b11387b1d439bc2905de4;hb=0ef165ecb57943e17a8ee8270df68ffb8d032e29;hp=866532156d3cae7348bf24d4dd5c3f689122beb2;hpb=4512aaa792c35cfb59710b951288f7a7394f3a73;p=sliver-openvswitch.git diff --git a/lib/smap.c b/lib/smap.c index 866532156..0d7573305 100644 --- a/lib/smap.c +++ b/lib/smap.c @@ -15,9 +15,10 @@ #include #include "smap.h" -#include +#include #include "hash.h" +#include "json.h" static struct smap_node *smap_add__(struct smap *, char *, void *, size_t hash); @@ -124,6 +125,31 @@ smap_remove_node(struct smap *smap, struct smap_node *node) free(node); } +/* Deletes 'node' from 'smap'. + * + * If 'keyp' is nonnull, stores the node's key in '*keyp' and transfers + * ownership to the caller. Otherwise, frees the node's key. Similarly for + * 'valuep' and the node's value. */ +void +smap_steal(struct smap *smap, struct smap_node *node, + char **keyp, char **valuep) +{ + if (keyp) { + *keyp = node->key; + } else { + free(node->key); + } + + if (valuep) { + *valuep = node->value; + } else { + free(node->value); + } + + hmap_remove(&smap->map, &node->node); + free(node); +} + /* Removes all key-value pairs from 'smap'. */ void smap_clear(struct smap *smap) @@ -225,13 +251,48 @@ smap_sort(const struct smap *smap) SMAP_FOR_EACH (node, smap) { nodes[i++] = node; } - assert(i == n); + ovs_assert(i == n); qsort(nodes, n, sizeof *nodes, compare_nodes_by_key); return nodes; } } + +/* Adds each of the key-value pairs from 'json' (which must be a JSON object + * whose values are strings) to 'smap'. + * + * The caller must have initialized 'smap'. + * + * The caller retains ownership of 'json' and everything in it. */ +void +smap_from_json(struct smap *smap, const struct json *json) +{ + const struct shash_node *node; + + SHASH_FOR_EACH (node, json_object(json)) { + const struct json *value = node->data; + smap_add(smap, node->name, json_string(value)); + } +} + +/* Returns a JSON object that maps from the keys in 'smap' to their values. + * + * The caller owns the returned value and must eventually json_destroy() it. + * + * The caller retains ownership of 'smap' and everything in it. */ +struct json * +smap_to_json(const struct smap *smap) +{ + const struct smap_node *node; + struct json *json; + + json = json_object_create(); + SMAP_FOR_EACH (node, smap) { + json_object_put_string(json, node->key, node->value); + } + return json; +} /* Private Helpers. */