[ovs-dev] [worker v2 11/14] smap: New functions smap_from_json(), smap_to_json().

Ben Pfaff blp at nicira.com
Wed Jun 27 18:25:27 UTC 2012


These will acquire a caller in an upcoming commit.

Signed-off-by: Ben Pfaff <blp at nicira.com>
---
 lib/smap.c |   36 ++++++++++++++++++++++++++++++++++++
 lib/smap.h |    5 +++++
 2 files changed, 41 insertions(+), 0 deletions(-)

diff --git a/lib/smap.c b/lib/smap.c
index 8665321..e612ac7 100644
--- a/lib/smap.c
+++ b/lib/smap.c
@@ -18,6 +18,7 @@
 #include <assert.h>
 
 #include "hash.h"
+#include "json.h"
 
 static struct smap_node *smap_add__(struct smap *, char *, void *,
                                     size_t hash);
@@ -232,6 +233,41 @@ smap_sort(const struct smap *smap)
         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. */
 
diff --git a/lib/smap.h b/lib/smap.h
index 51f6397..8510a37 100644
--- a/lib/smap.h
+++ b/lib/smap.h
@@ -17,6 +17,8 @@
 
 #include "hmap.h"
 
+struct json;
+
 /* A map from string to string. */
 struct smap {
     struct hmap map;           /* Contains "struct smap_node"s. */
@@ -60,4 +62,7 @@ size_t smap_count(const struct smap *);
 void smap_clone(struct smap *dst, const struct smap *src);
 const struct smap_node **smap_sort(const struct smap *);
 
+void smap_from_json(struct smap *, const struct json *);
+struct json *smap_to_json(const struct smap *);
+
 #endif /* smap.h */
-- 
1.7.2.5




More information about the dev mailing list