1/*
2* decorate.c - decorate a git object with some arbitrary
3* data.
4*/
5#include "cache.h"
6#include "object.h"
7#include "decorate.h"
89
static unsigned int hash_obj(struct object *obj, unsigned int n)
10{
11unsigned int hash = *(unsigned int *)obj->sha1;
12return hash % n;
13}
1415
static void *insert_decoration(struct decoration *n, struct object *base, void *decoration)
16{
17int size = n->size;
18struct object_decoration *hash = n->hash;
19int j = hash_obj(base, size);
2021
while (hash[j].base) {
22if (hash[j].base == base) {
23void *old = hash[j].decoration;
24hash[j].decoration = decoration;
25return old;
26}
27if (++j >= size)
28j = 0;
29}
30hash[j].base = base;
31hash[j].decoration = decoration;
32n->nr++;
33return NULL;
34}
3536
static void grow_decoration(struct decoration *n)
37{
38int i;
39int old_size = n->size;
40struct object_decoration *old_hash;
4142
old_size = n->size;
43old_hash = n->hash;
4445
n->size = (old_size + 1000) * 3 / 2;
46n->hash = xcalloc(n->size, sizeof(struct object_decoration));
47n->nr = 0;
4849
for (i = 0; i < old_size; i++) {
50struct object *base = old_hash[i].base;
51void *decoration = old_hash[i].decoration;
5253
if (!base)
54continue;
55insert_decoration(n, base, decoration);
56}
57free(old_hash);
58}
5960
/* Add a decoration pointer, return any old one */
61void *add_decoration(struct decoration *n, struct object *obj, void *decoration)
62{
63int nr = n->nr + 1;
6465
if (nr > n->size * 2 / 3)
66grow_decoration(n);
67return insert_decoration(n, obj, decoration);
68}
6970
/* Lookup a decoration pointer */
71void *lookup_decoration(struct decoration *n, struct object *obj)
72{
73int j;
7475
/* nothing to lookup */
76if (!n->size)
77return NULL;
78j = hash_obj(obj, n->size);
79for (;;) {
80struct object_decoration *ref = n->hash + j;
81if (ref->base == obj)
82return ref->decoration;
83if (!ref->base)
84return NULL;
85if (++j == n->size)
86j = 0;
87}
88}