preload-index.h: move declarations for preload-index.c from elsewhere
[alt-git.git] / decorate.c
blob71e79daa8259684f836f0addade83d644af91601
1 /*
2 * decorate.c - decorate a git object with some arbitrary
3 * data.
4 */
5 #include "git-compat-util.h"
6 #include "hashmap.h"
7 #include "object.h"
8 #include "decorate.h"
10 static unsigned int hash_obj(const struct object *obj, unsigned int n)
12 return oidhash(&obj->oid) % n;
15 static void *insert_decoration(struct decoration *n, const struct object *base, void *decoration)
17 int size = n->size;
18 struct decoration_entry *entries = n->entries;
19 unsigned int j = hash_obj(base, size);
21 while (entries[j].base) {
22 if (entries[j].base == base) {
23 void *old = entries[j].decoration;
24 entries[j].decoration = decoration;
25 return old;
27 if (++j >= size)
28 j = 0;
30 entries[j].base = base;
31 entries[j].decoration = decoration;
32 n->nr++;
33 return NULL;
36 static void grow_decoration(struct decoration *n)
38 int i;
39 int old_size = n->size;
40 struct decoration_entry *old_entries = n->entries;
42 n->size = (old_size + 1000) * 3 / 2;
43 CALLOC_ARRAY(n->entries, n->size);
44 n->nr = 0;
46 for (i = 0; i < old_size; i++) {
47 const struct object *base = old_entries[i].base;
48 void *decoration = old_entries[i].decoration;
50 if (!decoration)
51 continue;
52 insert_decoration(n, base, decoration);
54 free(old_entries);
57 void *add_decoration(struct decoration *n, const struct object *obj,
58 void *decoration)
60 int nr = n->nr + 1;
62 if (nr > n->size * 2 / 3)
63 grow_decoration(n);
64 return insert_decoration(n, obj, decoration);
67 void *lookup_decoration(struct decoration *n, const struct object *obj)
69 unsigned int j;
71 /* nothing to lookup */
72 if (!n->size)
73 return NULL;
74 j = hash_obj(obj, n->size);
75 for (;;) {
76 struct decoration_entry *ref = n->entries + j;
77 if (ref->base == obj)
78 return ref->decoration;
79 if (!ref->base)
80 return NULL;
81 if (++j == n->size)
82 j = 0;