offmap.c 1.85 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 "offmap.h"

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

17
__KHASH_TYPE(off, off64_t, void *)
18

19
__KHASH_IMPL(off, static kh_inline, off64_t, void *, 1, kh_int64_hash_func, kh_int64_hash_equal)
20

21 22

int git_offmap_new(git_offmap **out)
23
{
24 25 26 27
	*out = kh_init(off);
	GIT_ERROR_CHECK_ALLOC(*out);

	return 0;
28 29
}

30
void git_offmap_free(git_offmap *map)
31 32 33 34 35 36 37 38 39
{
	kh_destroy(off, map);
}

void git_offmap_clear(git_offmap *map)
{
	kh_clear(off, map);
}

40
size_t git_offmap_size(git_offmap *map)
41 42 43 44
{
	return kh_size(map);
}

45
void *git_offmap_get(git_offmap *map, const off64_t key)
46
{
47 48
	size_t idx = kh_get(off, map, key);
	if (idx == kh_end(map) || !kh_exist(map, idx))
49 50 51 52
		return NULL;
	return kh_val(map, idx);
}

53
int git_offmap_set(git_offmap *map, const off64_t key, void *value)
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
{
	size_t idx;
	int rval;

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

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

	kh_val(map, idx) = value;

	return 0;
}

70
int git_offmap_delete(git_offmap *map, const off64_t key)
71
{
72 73
	khiter_t idx = kh_get(off, map, key);
	if (idx == kh_end(map))
74
		return GIT_ENOTFOUND;
75
	kh_del(off, map, idx);
76 77
	return 0;
}
78

79
int git_offmap_exists(git_offmap *map, const off64_t key)
80 81 82 83
{
	return kh_get(off, map, key) != kh_end(map);
}

84
int git_offmap_iterate(void **value, git_offmap *map, size_t *iter, off64_t *key)
85 86 87
{
	size_t i = *iter;

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

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

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

	return 0;
}