oidmap.c 1.98 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 "oidmap.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(oid, const git_oid *, void *)

19 20 21 22 23 24 25
GIT_INLINE(khint_t) git_oidmap_hash(const git_oid *oid)
{
	khint_t h;
	memcpy(&h, oid, sizeof(khint_t));
	return h;
}

26 27
__KHASH_IMPL(oid, static kh_inline, const git_oid *, void *, 1, git_oidmap_hash, git_oid_equal)

28
int git_oidmap_new(git_oidmap **out)
29
{
30 31 32 33
	*out = kh_init(oid);
	GIT_ERROR_CHECK_ALLOC(*out);

	return 0;
34 35
}

36
void git_oidmap_free(git_oidmap *map)
37 38 39 40 41 42 43 44 45 46 47 48 49 50
{
	kh_destroy(oid, map);
}

void git_oidmap_clear(git_oidmap *map)
{
	kh_clear(oid, map);
}

size_t git_oidmap_size(git_oidmap *map)
{
	return kh_size(map);
}

51 52
void *git_oidmap_get(git_oidmap *map, const git_oid *key)
{
53 54
	size_t idx = kh_get(oid, map, key);
	if (idx == kh_end(map) || !kh_exist(map, idx))
55 56 57 58
		return NULL;
	return kh_val(map, idx);
}

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
int git_oidmap_set(git_oidmap *map, const git_oid *key, void *value)
{
	size_t idx;
	int rval;

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

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

	kh_val(map, idx) = value;

	return 0;
}

76 77
int git_oidmap_delete(git_oidmap *map, const git_oid *key)
{
78 79
	khiter_t idx = kh_get(oid, map, key);
	if (idx == kh_end(map))
80
		return GIT_ENOTFOUND;
81
	kh_del(oid, map, idx);
82 83 84
	return 0;
}

85 86 87 88 89
int git_oidmap_exists(git_oidmap *map, const git_oid *key)
{
	return kh_get(oid, map, key) != kh_end(map);
}

90 91 92 93
int git_oidmap_iterate(void **value, git_oidmap *map, size_t *iter, const git_oid **key)
{
	size_t i = *iter;

94
	while (i < map->n_buckets && !kh_exist(map, i))
95 96
		i++;

97
	if (i >= map->n_buckets)
98 99 100
		return GIT_ITEROVER;

	if (key)
101
		*key = kh_key(map, i);
102
	if (value)
103
		*value = kh_value(map, i);
104 105 106 107
	*iter = ++i;

	return 0;
}