decorate.con commit t0002: add test for enter_repo(), non-strict mode (3104120)
   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(const struct object *obj, unsigned int n)
  10{
  11        return sha1hash(obj->sha1) % n;
  12}
  13
  14static void *insert_decoration(struct decoration *n, const struct object *base, void *decoration)
  15{
  16        int size = n->size;
  17        struct object_decoration *hash = n->hash;
  18        unsigned int j = hash_obj(base, size);
  19
  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;
  25                }
  26                if (++j >= size)
  27                        j = 0;
  28        }
  29        hash[j].base = base;
  30        hash[j].decoration = decoration;
  31        n->nr++;
  32        return NULL;
  33}
  34
  35static void grow_decoration(struct decoration *n)
  36{
  37        int i;
  38        int old_size = n->size;
  39        struct object_decoration *old_hash = n->hash;
  40
  41        n->size = (old_size + 1000) * 3 / 2;
  42        n->hash = xcalloc(n->size, sizeof(struct object_decoration));
  43        n->nr = 0;
  44
  45        for (i = 0; i < old_size; i++) {
  46                const struct object *base = old_hash[i].base;
  47                void *decoration = old_hash[i].decoration;
  48
  49                if (!decoration)
  50                        continue;
  51                insert_decoration(n, base, decoration);
  52        }
  53        free(old_hash);
  54}
  55
  56/* Add a decoration pointer, return any old one */
  57void *add_decoration(struct decoration *n, const struct object *obj,
  58                void *decoration)
  59{
  60        int nr = n->nr + 1;
  61
  62        if (nr > n->size * 2 / 3)
  63                grow_decoration(n);
  64        return insert_decoration(n, obj, decoration);
  65}
  66
  67/* Lookup a decoration pointer */
  68void *lookup_decoration(struct decoration *n, const struct object *obj)
  69{
  70        unsigned int j;
  71
  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;
  84        }
  85}