From 0ff535b6f36e5d057eb9bbfef18bafff966df637 Mon Sep 17 00:00:00 2001 From: Krzysztof Opasiak Date: Wed, 31 May 2017 12:32:10 +0200 Subject: [PATCH] Add helpers for bson manipulation Change-Id: Iad2cefd42c3322a7d7d9a4fd66f3f939e88d87c7 Signed-off-by: Krzysztof Opasiak --- src/util/common.c | 33 +++++++++++++++++++++++++++++++++ src/util/common.h | 30 ++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/src/util/common.c b/src/util/common.c index 359ab87..3d3c910 100644 --- a/src/util/common.c +++ b/src/util/common.c @@ -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); +} diff --git a/src/util/common.h b/src/util/common.h index b874a43..6ae1cc2 100644 --- a/src/util/common.h +++ b/src/util/common.h @@ -22,6 +22,7 @@ #include #include #include +#include #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 */ -- 2.34.1