Fix init-db shared database case
[git/jnareb-git.git] / object.c
blobcfa2337641aabd692c659eabef347be11af9f517
1 #include "object.h"
2 #include "cache.h"
3 #include <stdlib.h>
4 #include <string.h>
6 struct object **objs;
7 int nr_objs;
8 static int obj_allocs;
10 static int find_object(unsigned char *sha1)
12 int first = 0, last = nr_objs;
14 while (first < last) {
15 int next = (first + last) / 2;
16 struct object *obj = objs[next];
17 int cmp;
19 cmp = memcmp(sha1, obj->sha1, 20);
20 if (!cmp)
21 return next;
22 if (cmp < 0) {
23 last = next;
24 continue;
26 first = next+1;
28 return -first-1;
31 struct object *lookup_object(unsigned char *sha1)
33 int pos = find_object(sha1);
34 if (pos >= 0)
35 return objs[pos];
36 return NULL;
39 void created_object(unsigned char *sha1, struct object *obj)
41 int pos = find_object(sha1);
43 obj->parsed = 0;
44 memcpy(obj->sha1, sha1, 20);
45 obj->type = NULL;
46 obj->refs = NULL;
47 obj->used = 0;
49 if (pos >= 0)
50 die("Inserting %s twice\n", sha1_to_hex(sha1));
51 pos = -pos-1;
53 if (obj_allocs == nr_objs) {
54 obj_allocs = alloc_nr(obj_allocs);
55 objs = realloc(objs, obj_allocs * sizeof(struct object *));
58 /* Insert it into the right place */
59 memmove(objs + pos + 1, objs + pos, (nr_objs - pos) *
60 sizeof(struct object *));
62 objs[pos] = obj;
63 nr_objs++;
66 void add_ref(struct object *refer, struct object *target)
68 struct object_list **pp = &refer->refs;
69 struct object_list *p;
71 while ((p = *pp) != NULL) {
72 if (p->item == target)
73 return;
74 pp = &p->next;
77 target->used = 1;
78 p = malloc(sizeof(*p));
79 p->item = target;
80 p->next = NULL;
81 *pp = p;
84 void mark_reachable(struct object *obj, unsigned int mask)
86 struct object_list *p = obj->refs;
88 /* If we've been here already, don't bother */
89 if (obj->flags & mask)
90 return;
91 obj->flags |= mask;
92 while (p) {
93 mark_reachable(p->item, mask);
94 p = p->next;