Add helpers for bson manipulation 07/132007/7
authorKrzysztof Opasiak <k.opasiak@samsung.com>
Wed, 31 May 2017 10:32:10 +0000 (12:32 +0200)
committerKrzysztof Opasiak <k.opasiak@samsung.com>
Mon, 5 Jun 2017 17:00:29 +0000 (19:00 +0200)
Change-Id: Iad2cefd42c3322a7d7d9a4fd66f3f939e88d87c7
Signed-off-by: Krzysztof Opasiak <k.opasiak@samsung.com>
src/util/common.c
src/util/common.h

index 359ab876f7fd0f92d3c0a1f01933fcff595ba714..3d3c910a9fe27de94132b4bec388353c9a3ce6a6 100644 (file)
@@ -25,3 +25,36 @@ GENERATE_BSON_APPEND_STRUCT(timespec,
                                                        bson_append_long(out, "sec", data->tv_sec);
                                                        bson_append_long(out, "nsec", data->tv_nsec);
                                                        )
+
+int bson_fill_empty(bson *b)
+{
+       int ret;
+
+       ret = faultd_bson_safe_init_size(b, BSON_EMPTY_SIZE);
+       if (ret != BSON_OK)
+               goto out;
+
+       ret = bson_finish(b);
+       if (ret != BSON_OK)
+               goto destroy;
+
+       return 0;
+destroy:
+       bson_destroy(b);
+out:
+       return -ENOMEM;
+}
+
+char *bson_get_string(bson *b, char *fieldpath)
+{
+       bson_iterator it;
+       int ret;
+
+       BSON_ITERATOR_INIT(&it, b);
+
+       ret = bson_find_fieldpath_value(fieldpath, &it);
+       if (ret == BSON_EOO || ret != BSON_STRING)
+               return NULL;
+
+       return (char *)bson_iterator_string(&it);
+}
index b874a43995a3ffa50eaa18395ce1bc7016cd7b52..6ae1cc222af104a0ad6e74a2532be691e052bf52 100644 (file)
@@ -22,6 +22,7 @@
 #include <ejdb/bson.h>
 #include <stdlib.h>
 #include <time.h>
+#include <errno.h>
 
 #define ARRAY_SIZE(a) (sizeof(a)/sizeof(*a))
 
@@ -62,4 +63,33 @@ static inline void freep(void *p)
 
 DECLARE_BSON_APPEND_STRUCT(timespec);
 
+#define BSON_EMPTY_SIZE (4 /* len */ + 1 /* \0 */)
+
+#define BSON_INITIAL_BUFFER_SIZE 128
+
+static inline int faultd_bson_safe_init_size(bson *b, int size)
+{
+       int ret;
+       /*
+        * TODO:
+        * For now ejdb does not provide bson constructors
+        * which return error if memory allocation fails.
+        * This wrapper should be removed when such functions
+        * become available.
+        */
+       bson_init_size(b, 0);
+       ret = bson_ensure_space(b, size);
+       if (ret != BSON_OK)
+               bson_destroy(b);
+
+       return ret;
+}
+
+#define faultd_bson_safe_init(b)                               \
+       faultd_bson_safe_init_size(b, BSON_INITIAL_BUFFER_SIZE)
+
+int bson_fill_empty(bson *b);
+
+char *bson_get_string(bson *b, char *fieldpath);
+
 #endif /* FAULTD_COMMON_H */