1 #include "git-compat-util.h"
4 int cmp_strmap_entry(const void *hashmap_cmp_fn_data,
5 const struct hashmap_entry *entry1,
6 const struct hashmap_entry *entry2,
9 const struct strmap_entry *e1, *e2;
11 e1 = container_of(entry1, const struct strmap_entry, ent);
12 e2 = container_of(entry2, const struct strmap_entry, ent);
13 return strcmp(e1->key, e2->key);
16 static struct strmap_entry *find_strmap_entry(struct strmap *map,
19 struct strmap_entry entry;
20 hashmap_entry_init(&entry.ent, strhash(str));
22 return hashmap_get_entry(&map->map, &entry, ent, NULL);
25 void strmap_init(struct strmap *map)
27 strmap_init_with_options(map, 1);
30 void strmap_init_with_options(struct strmap *map,
33 hashmap_init(&map->map, cmp_strmap_entry, NULL, 0);
34 map->strdup_strings = strdup_strings;
37 static void strmap_free_entries_(struct strmap *map, int free_values)
39 struct hashmap_iter iter;
40 struct strmap_entry *e;
46 * We need to iterate over the hashmap entries and free
47 * e->key and e->value ourselves; hashmap has no API to
48 * take care of that for us. Since we're already iterating over
49 * the hashmap, though, might as well free e too and avoid the need
50 * to make some call into the hashmap API to do that.
52 hashmap_for_each_entry(&map->map, &iter, e, ent) {
55 if (map->strdup_strings)
61 void strmap_clear(struct strmap *map, int free_values)
63 strmap_free_entries_(map, free_values);
64 hashmap_clear(&map->map);
67 void strmap_partial_clear(struct strmap *map, int free_values)
69 strmap_free_entries_(map, free_values);
70 hashmap_partial_clear(&map->map);
73 static struct strmap_entry *create_entry(struct strmap *map,
77 struct strmap_entry *entry;
78 const char *key = str;
80 entry = xmalloc(sizeof(*entry));
81 hashmap_entry_init(&entry->ent, strhash(str));
83 if (map->strdup_strings)
90 void *strmap_put(struct strmap *map, const char *str, void *data)
92 struct strmap_entry *entry = find_strmap_entry(map, str);
95 void *old = entry->value;
100 entry = create_entry(map, str, data);
101 hashmap_add(&map->map, &entry->ent);
105 struct strmap_entry *strmap_get_entry(struct strmap *map, const char *str)
107 return find_strmap_entry(map, str);
110 void *strmap_get(struct strmap *map, const char *str)
112 struct strmap_entry *entry = find_strmap_entry(map, str);
113 return entry ? entry->value : NULL;
116 int strmap_contains(struct strmap *map, const char *str)
118 return find_strmap_entry(map, str) != NULL;
121 void strmap_remove(struct strmap *map, const char *str, int free_value)
123 struct strmap_entry entry, *ret;
124 hashmap_entry_init(&entry.ent, strhash(str));
126 ret = hashmap_remove_entry(&map->map, &entry, ent, NULL);
131 if (map->strdup_strings)
132 free((char*)ret->key);
136 void strintmap_incr(struct strintmap *map, const char *str, intptr_t amt)
138 struct strmap_entry *entry = find_strmap_entry(&map->map, str);
140 intptr_t *whence = (intptr_t*)&entry->value;
144 strintmap_set(map, str, map->default_value + amt);