1 #include "git-compat-util.h"
3 #include "hash-lookup.h"
4 #include "read-cache-ll.h"
6 static uint32_t take2(const struct object_id
*oid
, size_t ofs
)
8 return ((oid
->hash
[ofs
] << 8) | oid
->hash
[ofs
+ 1]);
12 * Conventional binary search loop looks like this:
15 * int mi = lo + (hi - lo) / 2;
16 * int cmp = "entry pointed at by mi" minus "target";
18 * return (mi is the wanted one)
20 * hi = mi; "mi is larger than target"
22 * lo = mi+1; "mi is smaller than target"
27 * - When entering the loop, lo points at a slot that is never
28 * above the target (it could be at the target), hi points at a
29 * slot that is guaranteed to be above the target (it can never
32 * - We find a point 'mi' between lo and hi (mi could be the same
33 * as lo, but never can be the same as hi), and check if it hits
34 * the target. There are three cases:
36 * - if it is a hit, we are happy.
38 * - if it is strictly higher than the target, we update hi with
41 * - if it is strictly lower than the target, we update lo to be
42 * one slot after it, because we allow lo to be at the target.
44 * When choosing 'mi', we do not have to take the "middle" but
45 * anywhere in between lo and hi, as long as lo <= mi < hi is
46 * satisfied. When we somehow know that the distance between the
47 * target and lo is much shorter than the target and hi, we could
48 * pick mi that is much closer to lo than the midway.
51 * The table should contain "nr" elements.
52 * The oid of element i (between 0 and nr - 1) should be returned
55 int oid_pos(const struct object_id
*oid
, const void *table
, size_t nr
,
66 size_t lov
, hiv
, miv
, ofs
;
68 for (ofs
= 0; ofs
< the_hash_algo
->rawsz
- 2; ofs
+= 2) {
69 lov
= take2(fn(0, table
), ofs
);
70 hiv
= take2(fn(nr
- 1, table
), ofs
);
71 miv
= take2(oid
, ofs
);
75 return index_pos_to_insert_pos(nr
);
78 * At this point miv could be equal
79 * to hiv (but hash could still be higher);
80 * the invariant of (mi < hi) should be
83 mi
= (nr
- 1) * (miv
- lov
) / (hiv
- lov
);
84 if (lo
<= mi
&& mi
< hi
)
86 BUG("assertion failed in binary search");
93 cmp
= oidcmp(fn(mi
, table
), oid
);
100 mi
= lo
+ (hi
- lo
) / 2;
102 return index_pos_to_insert_pos(lo
);
105 int bsearch_hash(const unsigned char *hash
, const uint32_t *fanout_nbo
,
106 const unsigned char *table
, size_t stride
, uint32_t *result
)
110 hi
= ntohl(fanout_nbo
[*hash
]);
111 lo
= ((*hash
== 0x0) ? 0 : ntohl(fanout_nbo
[*hash
- 1]));
114 unsigned mi
= lo
+ (hi
- lo
) / 2;
115 int cmp
= hashcmp(table
+ mi
* stride
, hash
);