[PATCH 05/12] util/string-map: add _notmuch_string_map_deserialize

David Bremner david at tethera.net
Fri Jun 22 18:42:40 PDT 2018


The anticipated use case is loading the document data area from a
message Xapian document into a usable data structure.
---
 util/string-map.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++
 util/string-map.h |  8 ++++++++
 2 files changed, 57 insertions(+)

diff --git a/util/string-map.c b/util/string-map.c
index ab0c42ab..b29a9ba0 100644
--- a/util/string-map.c
+++ b/util/string-map.c
@@ -268,3 +268,52 @@ _notmuch_string_map_serialize (void* ctx, notmuch_string_map_t *map)
 
     return ret;
 }
+
+static char *
+unescape_newlines (void *ctx, const char *in, size_t len) {
+    size_t i,j;
+    /* removing escapes only makes things shorter */
+    char *out = talloc_zero_size (ctx, len+1);
+    for (i=0, j=0; i<len; i++) {
+	if (in[i] == '\\' && i < len - 1) {
+	    switch (in[i+1]) {
+	    case '\\':
+		i++;
+		out[j++] = '\\';
+		break;
+	    case 'n':
+		i++;
+		out[j++] = '\n';
+		break;
+	    default:
+		out[j++] = '\\';
+	    }
+	} else {
+	    out[j++] = in[i];
+	}
+    }
+    out[j]='\0';
+    return out;
+}
+
+notmuch_string_map_t *
+_notmuch_string_map_deserialize (void *ctx, const char *str)
+{
+    const char *tok = str;
+    const char *delim = "\n";
+    size_t tok_len = 0;
+    const char *pair [2];
+    size_t step = 0;
+
+    notmuch_string_map_t *map = _notmuch_string_map_create (ctx);
+
+    while ((tok = strtok_len_c (tok + tok_len, delim, &tok_len)) != NULL) {
+	pair[step] = unescape_newlines (ctx, tok, tok_len);
+	step++;
+	if (step == 2) {
+	    step = 0;
+	    _notmuch_string_map_append (map, pair[0], pair[1]);
+	}
+    }
+    return map;
+}
diff --git a/util/string-map.h b/util/string-map.h
index 9baf3530..22aa487c 100644
--- a/util/string-map.h
+++ b/util/string-map.h
@@ -40,4 +40,12 @@ _notmuch_string_map_iterator_destroy (notmuch_string_map_iterator_t *iterator);
  */
 const char *
 _notmuch_string_map_serialize (void *ctx, notmuch_string_map_t *map);
+
+/*
+ * decode newline delimited string "key1\nval1\key2\nval2\n..." into a string_map.
+ *
+ * \n decodes to newline and \\ decodes to \
+ */
+notmuch_string_map_t *
+_notmuch_string_map_deserialize (void *ctx, const char *str);
 #endif
-- 
2.17.1



More information about the notmuch mailing list