decorate.con commit fast-import: Fix crash when referencing already existing objects (20f546a)
   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"
   8
   9static unsigned int hash_obj(struct object *obj, unsigned int n)
  10{
  11        unsigned int hash = *(unsigned int *)obj->sha1;
  12        return hash % n;
  13}
  14
  15static void *insert_decoration(struct decoration *n, struct object *base, void *decoration)
  16{
  17        int size = n->size;
  18        struct object_decoration *hash = n->hash;
  19        int j = hash_obj(base, size);
  20
  21        while (hash[j].base) {
  22                if (hash[j].base == base) {
  23                        void *old = hash[j].decoration;
  24                        hash[j].decoration = decoration;
  25                        return old;
  26                }
  27                if (++j >= size)
  28                        j = 0;
  29        }
  30        hash[j].base = base;
  31        hash[j].decoration = decoration;
  32        n->nr++;
  33        return NULL;
  34}
  35
  36static void grow_decoration(struct decoration *n)
  37{
  38        int i;
  39        int old_size = n->size;
  40        struct object_decoration *old_hash;
  41
  42        old_size = n->size;
  43        old_hash = n->hash;
  44
  45        n->size = (old_size + 1000) * 3 / 2;
  46        n->hash = xcalloc(n->size, sizeof(struct object_decoration));
  47        n->nr = 0;
  48
  49        for (i = 0; i < old_size; i++) {
  50                struct object *base = old_hash[i].base;
  51                void *decoration = old_hash[i].decoration;
  52
  53                if (!base)
  54                        continue;
  55                insert_decoration(n, base, decoration);
  56        }
  57        free(old_hash);
  58}
  59
  60/* Add a decoration pointer, return any old one */
  61void *add_decoration(struct decoration *n, struct object *obj, void *decoration)
  62{
  63        int nr = n->nr + 1;
  64
  65        if (nr > n->size * 2 / 3)
  66                grow_decoration(n);
  67        return insert_decoration(n, obj, decoration);
  68}
  69
  70/* Lookup a decoration pointer */
  71void *lookup_decoration(struct decoration *n, struct object *obj)
  72{
  73        int j;
  74
  75        /* nothing to lookup */
  76        if (!n->size)
  77                return NULL;
  78        j = hash_obj(obj, n->size);
  79        for (;;) {
  80                struct object_decoration *ref = n->hash + j;
  81                if (ref->base == obj)
  82                        return ref->decoration;
  83                if (!ref->base)
  84                        return NULL;
  85                if (++j == n->size)
  86                        j = 0;
  87        }
  88}