git
/
decorate.c
98 строк · 2.0 Кб
1/*
2* decorate.c - decorate a git object with some arbitrary
3* data.
4*/
5#include "git-compat-util.h"6#include "object.h"7#include "decorate.h"8
9static unsigned int hash_obj(const struct object *obj, unsigned int n)10{
11return oidhash(&obj->oid) % n;12}
13
14static void *insert_decoration(struct decoration *n, const struct object *base, void *decoration)15{
16int size = n->size;17struct decoration_entry *entries = n->entries;18unsigned int j = hash_obj(base, size);19
20while (entries[j].base) {21if (entries[j].base == base) {22void *old = entries[j].decoration;23entries[j].decoration = decoration;24return old;25}26if (++j >= size)27j = 0;28}29entries[j].base = base;30entries[j].decoration = decoration;31n->nr++;32return NULL;33}
34
35static void grow_decoration(struct decoration *n)36{
37int i;38int old_size = n->size;39struct decoration_entry *old_entries = n->entries;40
41n->size = (old_size + 1000) * 3 / 2;42CALLOC_ARRAY(n->entries, n->size);43n->nr = 0;44
45for (i = 0; i < old_size; i++) {46const struct object *base = old_entries[i].base;47void *decoration = old_entries[i].decoration;48
49if (!decoration)50continue;51insert_decoration(n, base, decoration);52}53free(old_entries);54}
55
56void *add_decoration(struct decoration *n, const struct object *obj,57void *decoration)58{
59int nr = n->nr + 1;60
61if (nr > n->size * 2 / 3)62grow_decoration(n);63return insert_decoration(n, obj, decoration);64}
65
66void *lookup_decoration(struct decoration *n, const struct object *obj)67{
68unsigned int j;69
70/* nothing to lookup */71if (!n->size)72return NULL;73j = hash_obj(obj, n->size);74for (;;) {75struct decoration_entry *ref = n->entries + j;76if (ref->base == obj)77return ref->decoration;78if (!ref->base)79return NULL;80if (++j == n->size)81j = 0;82}83}
84
85void clear_decoration(struct decoration *n, void (*free_cb)(void *))86{
87if (free_cb) {88unsigned int i;89for (i = 0; i < n->size; i++) {90void *d = n->entries[i].decoration;91if (d)92free_cb(d);93}94}95
96FREE_AND_NULL(n->entries);97n->size = n->nr = 0;98}
99