strmap.c 1.84 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*
 * Copyright (C) the libgit2 contributors. All rights reserved.
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */

#include "strmap.h"

10 11 12 13 14 15 16 17 18
#define kmalloc git__malloc
#define kcalloc git__calloc
#define krealloc git__realloc
#define kreallocarray git__reallocarray
#define kfree git__free
#include "khash.h"

__KHASH_TYPE(str, const char *, void *)

19
__KHASH_IMPL(str, static kh_inline, const char *, void *, 1, kh_str_hash_func, kh_str_hash_equal)
20

21
int git_strmap_new(git_strmap **out)
22
{
23 24
	*out = kh_init(str);
	GIT_ERROR_CHECK_ALLOC(*out);
25 26 27 28

	return 0;
}

29
void git_strmap_free(git_strmap *map)
30 31 32 33 34 35 36 37 38
{
	kh_destroy(str, map);
}

void git_strmap_clear(git_strmap *map)
{
	kh_clear(str, map);
}

39
size_t git_strmap_size(git_strmap *map)
40 41 42 43
{
	return kh_size(map);
}

44 45
void *git_strmap_get(git_strmap *map, const char *key)
{
46 47
	size_t idx = kh_get(str, map, key);
	if (idx == kh_end(map) || !kh_exist(map, idx))
48 49 50 51
		return NULL;
	return kh_val(map, idx);
}

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
int git_strmap_set(git_strmap *map, const char *key, void *value)
{
	size_t idx;
	int rval;

	idx = kh_put(str, map, key, &rval);
	if (rval < 0)
		return -1;

	if (rval == 0)
		kh_key(map, idx) = key;

	kh_val(map, idx) = value;

	return 0;
}

69 70
int git_strmap_delete(git_strmap *map, const char *key)
{
71 72
	khiter_t idx = kh_get(str, map, key);
	if (idx == kh_end(map))
73
		return GIT_ENOTFOUND;
74
	kh_del(str, map, idx);
75 76 77
	return 0;
}

78 79 80 81 82
int git_strmap_exists(git_strmap *map, const char *key)
{
	return kh_get(str, map, key) != kh_end(map);
}

83 84 85 86
int git_strmap_iterate(void **value, git_strmap *map, size_t *iter, const char **key)
{
	size_t i = *iter;

87
	while (i < map->n_buckets && !kh_exist(map, i))
88 89
		i++;

90
	if (i >= map->n_buckets)
91 92 93
		return GIT_ITEROVER;

	if (key)
94
		*key = kh_key(map, i);
95
	if (value)
96
		*value = kh_val(map, i);
97 98 99 100
	*iter = ++i;

	return 0;
}