oidset: use khash
[git/git.git] / oidset.h
CommitLineData
29c2bd5f
JK
1#ifndef OIDSET_H
2#define OIDSET_H
3
8b2f8cbc
RS
4#include "hashmap.h"
5#include "khash.h"
9e6fabde 6
29c2bd5f
JK
7/**
8 * This API is similar to sha1-array, in that it maintains a set of object ids
9 * in a memory-efficient way. The major differences are:
10 *
11 * 1. It uses a hash, so we can do online duplicate removal, rather than
12 * sort-and-uniq at the end. This can reduce memory footprint if you have
13 * a large list of oids with many duplicates.
14 *
15 * 2. The per-unique-oid memory footprint is slightly higher due to hash
16 * table overhead.
17 */
18
8b2f8cbc
RS
19static inline unsigned int oid_hash(struct object_id oid)
20{
21 return sha1hash(oid.hash);
22}
23
24static inline int oid_equal(struct object_id a, struct object_id b)
25{
26 return oideq(&a, &b);
27}
28
29KHASH_INIT(oid, struct object_id, int, 0, oid_hash, oid_equal)
30
29c2bd5f
JK
31/**
32 * A single oidset; should be zero-initialized (or use OIDSET_INIT).
33 */
34struct oidset {
8b2f8cbc 35 kh_oid_t set;
29c2bd5f
JK
36};
37
8b2f8cbc 38#define OIDSET_INIT { { 0 } }
29c2bd5f 39
c3a9ad31
JH
40
41static inline void oidset_init(struct oidset *set, size_t initial_size)
42{
8b2f8cbc
RS
43 memset(&set->set, 0, sizeof(set->set));
44 if (initial_size)
45 kh_resize_oid(&set->set, initial_size);
c3a9ad31
JH
46}
47
29c2bd5f
JK
48/**
49 * Returns true iff `set` contains `oid`.
50 */
51int oidset_contains(const struct oidset *set, const struct object_id *oid);
52
53/**
54 * Insert the oid into the set; a copy is made, so "oid" does not need
55 * to persist after this function is called.
56 *
57 * Returns 1 if the oid was already in the set, 0 otherwise. This can be used
58 * to perform an efficient check-and-add.
59 */
60int oidset_insert(struct oidset *set, const struct object_id *oid);
61
c3a9ad31
JH
62/**
63 * Remove the oid from the set.
64 *
65 * Returns 1 if the oid was present in the set, 0 otherwise.
66 */
67int oidset_remove(struct oidset *set, const struct object_id *oid);
68
29c2bd5f
JK
69/**
70 * Remove all entries from the oidset, freeing any resources associated with
71 * it.
72 */
73void oidset_clear(struct oidset *set);
74
c3a9ad31 75struct oidset_iter {
8b2f8cbc
RS
76 kh_oid_t *set;
77 khiter_t iter;
c3a9ad31
JH
78};
79
80static inline void oidset_iter_init(struct oidset *set,
81 struct oidset_iter *iter)
82{
8b2f8cbc
RS
83 iter->set = &set->set;
84 iter->iter = kh_begin(iter->set);
c3a9ad31
JH
85}
86
87static inline struct object_id *oidset_iter_next(struct oidset_iter *iter)
88{
8b2f8cbc
RS
89 for (; iter->iter != kh_end(iter->set); iter->iter++) {
90 if (kh_exist(iter->set, iter->iter))
91 return &kh_key(iter->set, iter->iter++);
92 }
93 return NULL;
c3a9ad31
JH
94}
95
96static inline struct object_id *oidset_iter_first(struct oidset *set,
97 struct oidset_iter *iter)
98{
99 oidset_iter_init(set, iter);
100 return oidset_iter_next(iter);
101}
102
29c2bd5f 103#endif /* OIDSET_H */