1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
5 #include "hash-lookup.h"
6 #include "read-cache-ll.h"
8 static uint32_t take2(const struct object_id
*oid
, size_t ofs
)
10 return ((oid
->hash
[ofs
] << 8) | oid
->hash
[ofs
+ 1]);
14 * Conventional binary search loop looks like this:
17 * int mi = lo + (hi - lo) / 2;
18 * int cmp = "entry pointed at by mi" minus "target";
20 * return (mi is the wanted one)
22 * hi = mi; "mi is larger than target"
24 * lo = mi+1; "mi is smaller than target"
29 * - When entering the loop, lo points at a slot that is never
30 * above the target (it could be at the target), hi points at a
31 * slot that is guaranteed to be above the target (it can never
34 * - We find a point 'mi' between lo and hi (mi could be the same
35 * as lo, but never can be the same as hi), and check if it hits
36 * the target. There are three cases:
38 * - if it is a hit, we are happy.
40 * - if it is strictly higher than the target, we update hi with
43 * - if it is strictly lower than the target, we update lo to be
44 * one slot after it, because we allow lo to be at the target.
46 * When choosing 'mi', we do not have to take the "middle" but
47 * anywhere in between lo and hi, as long as lo <= mi < hi is
48 * satisfied. When we somehow know that the distance between the
49 * target and lo is much shorter than the target and hi, we could
50 * pick mi that is much closer to lo than the midway.
53 * The table should contain "nr" elements.
54 * The oid of element i (between 0 and nr - 1) should be returned
57 int oid_pos(const struct object_id
*oid
, const void *table
, size_t nr
,
68 size_t lov
, hiv
, miv
, ofs
;
70 for (ofs
= 0; ofs
< the_hash_algo
->rawsz
- 2; ofs
+= 2) {
71 lov
= take2(fn(0, table
), ofs
);
72 hiv
= take2(fn(nr
- 1, table
), ofs
);
73 miv
= take2(oid
, ofs
);
77 return index_pos_to_insert_pos(nr
);
80 * At this point miv could be equal
81 * to hiv (but hash could still be higher);
82 * the invariant of (mi < hi) should be
85 mi
= (nr
- 1) * (miv
- lov
) / (hiv
- lov
);
86 if (lo
<= mi
&& mi
< hi
)
88 BUG("assertion failed in binary search");
95 cmp
= oidcmp(fn(mi
, table
), oid
);
102 mi
= lo
+ (hi
- lo
) / 2;
104 return index_pos_to_insert_pos(lo
);
107 int bsearch_hash(const unsigned char *hash
, const uint32_t *fanout_nbo
,
108 const unsigned char *table
, size_t stride
, uint32_t *result
)
112 hi
= ntohl(fanout_nbo
[*hash
]);
113 lo
= ((*hash
== 0x0) ? 0 : ntohl(fanout_nbo
[*hash
- 1]));
116 unsigned mi
= lo
+ (hi
- lo
) / 2;
117 int cmp
= hashcmp(table
+ mi
* stride
, hash
,
118 the_repository
->hash_algo
);