1 /* string-map.c - associative arrays of strings
4 * Copyright © 2016 David Bremner
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see http://www.gnu.org/licenses/ .
19 * Author: David Bremner <david@tethera.net>
22 #include "notmuch-private.h"
24 /* Create a new notmuch_string_map_t object, with 'ctx' as its
27 * This function can return NULL in case of out-of-memory.
30 typedef struct _notmuch_string_pair_t {
33 } notmuch_string_pair_t;
35 struct _notmuch_string_map {
36 notmuch_bool_t sorted;
38 notmuch_string_pair_t *pairs;
41 notmuch_string_map_t *
42 _notmuch_string_map_create (const void *ctx)
44 notmuch_string_map_t *map;
46 map = talloc (ctx, notmuch_string_map_t);
47 if (unlikely (map == NULL))
58 _notmuch_string_map_append (notmuch_string_map_t *map,
67 map->pairs = talloc_realloc (map, map->pairs, notmuch_string_pair_t, map->length + 1);
69 map->pairs = talloc_array (map, notmuch_string_pair_t, map->length + 1);
71 map->pairs[map->length - 1].key = talloc_strdup (map, key);
72 map->pairs[map->length - 1].value = talloc_strdup (map, value);
75 map->pairs[map->length].key = NULL;
76 map->pairs[map->length].value = NULL;
81 cmppair (const void *pa, const void *pb)
83 notmuch_string_pair_t *a = (notmuch_string_pair_t *) pa;
84 notmuch_string_pair_t *b = (notmuch_string_pair_t *) pb;
86 return strcmp (a->key, b->key);
90 _notmuch_string_map_sort (notmuch_string_map_t *map)
98 qsort (map->pairs, map->length, sizeof (notmuch_string_pair_t), cmppair);
103 static notmuch_bool_t
104 string_cmp (const char *a, const char *b, notmuch_bool_t exact)
107 return (strcmp (a, b));
109 return (strncmp (a, b, strlen (a)));
112 static notmuch_string_pair_t *
113 bsearch_first (notmuch_string_pair_t *array, size_t len, const char *key, notmuch_bool_t exact)
116 size_t last = len - 1;
122 while (last > first) {
123 mid = (first + last) / 2;
124 int sign = string_cmp (key, array[mid].key, exact);
133 if (string_cmp (key, array[first].key, exact) == 0)
134 return array + first;
141 _notmuch_string_map_get (notmuch_string_map_t *map, const char *key)
143 notmuch_string_pair_t *pair;
145 /* this means that calling append invalidates iterators */
146 _notmuch_string_map_sort (map);
148 pair = bsearch_first (map->pairs, map->length, key, TRUE);