aboutsummaryrefslogtreecommitdiff
path: root/src/map.c
diff options
context:
space:
mode:
authorThiago de Arruda <tpadilha84@gmail.com>2014-05-07 17:56:57 -0300
committerThiago de Arruda <tpadilha84@gmail.com>2014-05-12 19:28:25 -0300
commit51ee26fe687facb730a5d96c71bb169dafc1d67e (patch)
treec6cc70e37a86efbcace22299462d3854db1795fe /src/map.c
parent5b7a9d578033aad77a9e34dee83b8402c595fcbe (diff)
downloadrneovim-51ee26fe687facb730a5d96c71bb169dafc1d67e.tar.gz
rneovim-51ee26fe687facb730a5d96c71bb169dafc1d67e.tar.bz2
rneovim-51ee26fe687facb730a5d96c71bb169dafc1d67e.zip
Implement generic map on top of khash
Implement a generic string->pointer associative array on top of the khash macro library, providing a nice API for simple hash table requirements. (khash gives lot of control with a not-so-friendly API, which is unnecessary on most cases)
Diffstat (limited to 'src/map.c')
-rw-r--r--src/map.c91
1 files changed, 91 insertions, 0 deletions
diff --git a/src/map.c b/src/map.c
new file mode 100644
index 0000000000..3e2bbe03e0
--- /dev/null
+++ b/src/map.c
@@ -0,0 +1,91 @@
+#include <stdlib.h>
+#include <stdbool.h>
+
+#include "map.h"
+#include "map_defs.h"
+#include "vim.h"
+#include "memory.h"
+
+#include "lib/khash.h"
+
+typedef struct {
+ void *ptr;
+} Value;
+
+KHASH_MAP_INIT_STR(Map, Value)
+
+struct map {
+ khash_t(Map) *table;
+};
+
+Map *map_new()
+{
+ Map *rv = xmalloc(sizeof(Map));
+ rv->table = kh_init(Map);
+ return rv;
+}
+
+void map_free(Map *map)
+{
+ kh_clear(Map, map->table);
+ kh_destroy(Map, map->table);
+ free(map);
+}
+
+void *map_get(Map *map, const char *key)
+{
+ khiter_t k;
+
+ if ((k = kh_get(Map, map->table, key)) == kh_end(map->table)) {
+ return NULL;
+ }
+
+ return kh_val(map->table, k).ptr;
+}
+
+bool map_has(Map *map, const char *key)
+{
+ return map_get(map, key) != NULL;
+}
+
+void *map_put(Map *map, const char *key, void *value)
+{
+ int ret;
+ void *rv = NULL;
+ khiter_t k = kh_put(Map, map->table, key, &ret);
+ Value val = {.ptr = value};
+
+ if (!ret) {
+ // key present, return the current value
+ rv = kh_val(map->table, k).ptr;
+ kh_del(Map, map->table, k);
+ }
+
+ kh_val(map->table, k) = val;
+
+ return rv;
+}
+
+void *map_del(Map *map, const char *key)
+{
+ void *rv = NULL;
+ khiter_t k;
+
+ if ((k = kh_get(Map, map->table, key)) != kh_end(map->table)) {
+ rv = kh_val(map->table, k).ptr;
+ kh_del(Map, map->table, k);
+ }
+
+ return rv;
+}
+
+void map_foreach(Map *map, key_value_cb cb)
+{
+ const char *key;
+ Value value;
+
+ kh_foreach(map->table, key, value, {
+ cb(map, (const char *)key, value.ptr);
+ });
+}
+