[PATCH 07/12] util/string-map: add _notmuch_string_map_set

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


In contrast to the existing _append, this is intended for interleaved
read and write operations.
---
 test/T710-string-map.sh | 30 ++++++++++++++++++++++++++++++
 util/string-map.c       | 19 +++++++++++++++++++
 util/string-map.h       |  5 +++++
 3 files changed, 54 insertions(+)

diff --git a/test/T710-string-map.sh b/test/T710-string-map.sh
index 8fd69a53..6f07f363 100755
--- a/test/T710-string-map.sh
+++ b/test/T710-string-map.sh
@@ -97,6 +97,36 @@ val[2]=testval2
 EOF
 test_expect_equal_file EXPECTED OUTPUT
 
+test_begin_subtest "set (replace)"
+cat c_head - c_tail <<'EOF' | test_C $
+{
+    notmuch_string_map_t *map = _notmuch_string_map_create(ctx);
+    _notmuch_string_map_append (map, "testkey1", "testval1");
+    _notmuch_string_map_append (map, "testkey2", "testval2");
+    _notmuch_string_map_append (map, "testkey1", "testval3");
+    dump_map (map);
+    _notmuch_string_map_set (map, "testkey1", "newval");
+    dump_map (map);
+}
+EOF
+cat<<EOF > EXPECTED
+== stdout ==
+key[0]=testkey1
+val[0]=testval1
+key[1]=testkey1
+val[1]=testval3
+key[2]=testkey2
+val[2]=testval2
+key[0]=testkey1
+val[0]=newval
+key[1]=testkey1
+val[1]=testval3
+key[2]=testkey2
+val[2]=testval2
+== stderr ==
+EOF
+test_expect_equal_file EXPECTED OUTPUT
+
 test_begin_subtest "get first"
 cat c_head - c_tail <<'EOF' | test_C $
 {
diff --git a/util/string-map.c b/util/string-map.c
index b29a9ba0..41a6881d 100644
--- a/util/string-map.c
+++ b/util/string-map.c
@@ -143,6 +143,25 @@ bsearch_first (notmuch_string_pair_t *array, size_t len, const char *key, bool e
 
 }
 
+void
+_notmuch_string_map_set (notmuch_string_map_t *map,
+			     const char *key,
+			     const char *value)
+{
+
+    notmuch_string_pair_t *pair;
+
+    /* this means that calling append invalidates iterators */
+    _notmuch_string_map_sort (map);
+
+    pair = bsearch_first (map->pairs, map->length, key, true);
+    if (! pair)
+	_notmuch_string_map_append (map, key, value);
+
+    pair->value = talloc_strdup (map, value);
+
+}
+
 const char *
 _notmuch_string_map_get (notmuch_string_map_t *map, const char *key)
 {
diff --git a/util/string-map.h b/util/string-map.h
index 22aa487c..ff648b5c 100644
--- a/util/string-map.h
+++ b/util/string-map.h
@@ -12,6 +12,11 @@ _notmuch_string_map_append (notmuch_string_map_t *map,
 			    const char *key,
 			    const char *value);
 
+void
+_notmuch_string_map_set (notmuch_string_map_t *map,
+			 const char *key,
+			 const char *value);
+
 const char *
 _notmuch_string_map_get (notmuch_string_map_t *map, const char *key);
 
-- 
2.17.1



More information about the notmuch mailing list