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{
11unsigned int hash;
1213
memcpy(&hash, obj->sha1, sizeof(unsigned int));
14return hash % n;
15}
1617
static void *insert_decoration(struct decoration *n, const struct object *base, void *decoration)
18{
19int size = n->size;
20struct object_decoration *hash = n->hash;
21unsigned int j = hash_obj(base, size);
2223
while (hash[j].base) {
24if (hash[j].base == base) {
25void *old = hash[j].decoration;
26hash[j].decoration = decoration;
27return old;
28}
29if (++j >= size)
30j = 0;
31}
32hash[j].base = base;
33hash[j].decoration = decoration;
34n->nr++;
35return NULL;
36}
3738
static void grow_decoration(struct decoration *n)
39{
40int i;
41int old_size = n->size;
42struct object_decoration *old_hash = n->hash;
4344
n->size = (old_size + 1000) * 3 / 2;
45n->hash = xcalloc(n->size, sizeof(struct object_decoration));
46n->nr = 0;
4748
for (i = 0; i < old_size; i++) {
49const struct object *base = old_hash[i].base;
50void *decoration = old_hash[i].decoration;
5152
if (!decoration)
53continue;
54insert_decoration(n, base, decoration);
55}
56free(old_hash);
57}
5859
/* Add a decoration pointer, return any old one */
60void *add_decoration(struct decoration *n, const struct object *obj,
61void *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, const struct object *obj)
72{
73unsigned int 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}