1#include "object.h"
2#include "cache.h"
3#include <stdlib.h>
4#include <string.h>
5
6struct object **objs;
7int nr_objs;
8static int obj_allocs;
9
10static int find_object(unsigned char *sha1)
11{
12 int first = 0, last = nr_objs;
13
14 while (first < last) {
15 int next = (first + last) / 2;
16 struct object *obj = objs[next];
17 int cmp;
18
19 cmp = memcmp(sha1, obj->sha1, 20);
20 if (!cmp)
21 return next;
22 if (cmp < 0) {
23 last = next;
24 continue;
25 }
26 first = next+1;
27 }
28 return -first-1;
29}
30
31struct object *lookup_object(unsigned char *sha1)
32{
33 int pos = find_object(sha1);
34 if (pos >= 0)
35 return objs[pos];
36 return NULL;
37}
38
39void created_object(unsigned char *sha1, struct object *obj)
40{
41 int pos = find_object(sha1);
42
43 obj->parsed = 0;
44 memcpy(obj->sha1, sha1, 20);
45 obj->type = NULL;
46 obj->refs = NULL;
47 obj->used = 0;
48
49 if (pos >= 0)
50 die("Inserting %s twice\n", sha1_to_hex(sha1));
51 pos = -pos-1;
52
53 if (obj_allocs == nr_objs) {
54 obj_allocs = alloc_nr(obj_allocs);
55 objs = realloc(objs, obj_allocs * sizeof(struct object *));
56 }
57
58 /* Insert it into the right place */
59 memmove(objs + pos + 1, objs + pos, (nr_objs - pos) *
60 sizeof(struct object *));
61
62 objs[pos] = obj;
63 nr_objs++;
64}
65
66void add_ref(struct object *refer, struct object *target)
67{
68 struct object_list **pp = &refer->refs;
69 struct object_list *p;
70
71 while ((p = *pp) != NULL) {
72 if (p->item == target)
73 return;
74 pp = &p->next;
75 }
76
77 target->used = 1;
78 p = malloc(sizeof(*p));
79 p->item = target;
80 p->next = NULL;
81 *pp = p;
82}
83
84void mark_reachable(struct object *obj, unsigned int mask)
85{
86 struct object_list *p = obj->refs;
87
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;
95 }
96}