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(const struct object *obj, unsigned int n)
10{
11return sha1hash(obj->oid.hash) % n;
12}
1314
static void *insert_decoration(struct decoration *n, const struct object *base, void *decoration)
15{
16int size = n->size;
17struct object_decoration *hash = n->hash;
18unsigned int j = hash_obj(base, size);
1920
while (hash[j].base) {
21if (hash[j].base == base) {
22void *old = hash[j].decoration;
23hash[j].decoration = decoration;
24return old;
25}
26if (++j >= size)
27j = 0;
28}
29hash[j].base = base;
30hash[j].decoration = decoration;
31n->nr++;
32return NULL;
33}
3435
static void grow_decoration(struct decoration *n)
36{
37int i;
38int old_size = n->size;
39struct object_decoration *old_hash = n->hash;
4041
n->size = (old_size + 1000) * 3 / 2;
42n->hash = xcalloc(n->size, sizeof(struct object_decoration));
43n->nr = 0;
4445
for (i = 0; i < old_size; i++) {
46const struct object *base = old_hash[i].base;
47void *decoration = old_hash[i].decoration;
4849
if (!decoration)
50continue;
51insert_decoration(n, base, decoration);
52}
53free(old_hash);
54}
5556
/* Add a decoration pointer, return any old one */
57void *add_decoration(struct decoration *n, const struct object *obj,
58void *decoration)
59{
60int nr = n->nr + 1;
6162
if (nr > n->size * 2 / 3)
63grow_decoration(n);
64return insert_decoration(n, obj, decoration);
65}
6667
/* Lookup a decoration pointer */
68void *lookup_decoration(struct decoration *n, const struct object *obj)
69{
70unsigned int j;
7172
/* nothing to lookup */
73if (!n->size)
74return NULL;
75j = hash_obj(obj, n->size);
76for (;;) {
77struct object_decoration *ref = n->hash + j;
78if (ref->base == obj)
79return ref->decoration;
80if (!ref->base)
81return NULL;
82if (++j == n->size)
83j = 0;
84}
85}