Git 2.1.0-rc1
[git/git-svn.git] / decorate.c
blobb2aac90c26296eacdd6c2cdb68a15f3744c595e9
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"
9 static unsigned int hash_obj(const struct object *obj, unsigned int n)
11 return sha1hash(obj->sha1) % n;
14 static void *insert_decoration(struct decoration *n, const struct object *base, void *decoration)
16 int size = n->size;
17 struct object_decoration *hash = n->hash;
18 unsigned int j = hash_obj(base, size);
20 while (hash[j].base) {
21 if (hash[j].base == base) {
22 void *old = hash[j].decoration;
23 hash[j].decoration = decoration;
24 return old;
26 if (++j >= size)
27 j = 0;
29 hash[j].base = base;
30 hash[j].decoration = decoration;
31 n->nr++;
32 return NULL;
35 static void grow_decoration(struct decoration *n)
37 int i;
38 int old_size = n->size;
39 struct object_decoration *old_hash = n->hash;
41 n->size = (old_size + 1000) * 3 / 2;
42 n->hash = xcalloc(n->size, sizeof(struct object_decoration));
43 n->nr = 0;
45 for (i = 0; i < old_size; i++) {
46 const struct object *base = old_hash[i].base;
47 void *decoration = old_hash[i].decoration;
49 if (!decoration)
50 continue;
51 insert_decoration(n, base, decoration);
53 free(old_hash);
56 /* Add a decoration pointer, return any old one */
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 /* Lookup a decoration pointer */
68 void *lookup_decoration(struct decoration *n, const struct object *obj)
70 unsigned int j;
72 /* nothing to lookup */
73 if (!n->size)
74 return NULL;
75 j = hash_obj(obj, n->size);
76 for (;;) {
77 struct object_decoration *ref = n->hash + j;
78 if (ref->base == obj)
79 return ref->decoration;
80 if (!ref->base)
81 return NULL;
82 if (++j == n->size)
83 j = 0;