Merge branch 'ds/trace2-regions-in-tests'
[git/debian.git] / reftable / basics.c
blobf761e48028c4490e40728fd2879a7520297a0e41
1 /*
2 Copyright 2020 Google LLC
4 Use of this source code is governed by a BSD-style
5 license that can be found in the LICENSE file or at
6 https://developers.google.com/open-source/licenses/bsd
7 */
9 #include "basics.h"
11 void put_be24(uint8_t *out, uint32_t i)
13 out[0] = (uint8_t)((i >> 16) & 0xff);
14 out[1] = (uint8_t)((i >> 8) & 0xff);
15 out[2] = (uint8_t)(i & 0xff);
18 uint32_t get_be24(uint8_t *in)
20 return (uint32_t)(in[0]) << 16 | (uint32_t)(in[1]) << 8 |
21 (uint32_t)(in[2]);
24 void put_be16(uint8_t *out, uint16_t i)
26 out[0] = (uint8_t)((i >> 8) & 0xff);
27 out[1] = (uint8_t)(i & 0xff);
30 int binsearch(size_t sz, int (*f)(size_t k, void *args), void *args)
32 size_t lo = 0;
33 size_t hi = sz;
35 /* Invariants:
37 * (hi == sz) || f(hi) == true
38 * (lo == 0 && f(0) == true) || fi(lo) == false
40 while (hi - lo > 1) {
41 size_t mid = lo + (hi - lo) / 2;
43 if (f(mid, args))
44 hi = mid;
45 else
46 lo = mid;
49 if (lo)
50 return hi;
52 return f(0, args) ? 0 : 1;
55 void free_names(char **a)
57 char **p;
58 if (!a) {
59 return;
61 for (p = a; *p; p++) {
62 reftable_free(*p);
64 reftable_free(a);
67 int names_length(char **names)
69 char **p = names;
70 for (; *p; p++) {
71 /* empty */
73 return p - names;
76 void parse_names(char *buf, int size, char ***namesp)
78 char **names = NULL;
79 size_t names_cap = 0;
80 size_t names_len = 0;
82 char *p = buf;
83 char *end = buf + size;
84 while (p < end) {
85 char *next = strchr(p, '\n');
86 if (next && next < end) {
87 *next = 0;
88 } else {
89 next = end;
91 if (p < next) {
92 if (names_len == names_cap) {
93 names_cap = 2 * names_cap + 1;
94 names = reftable_realloc(
95 names, names_cap * sizeof(*names));
97 names[names_len++] = xstrdup(p);
99 p = next + 1;
102 names = reftable_realloc(names, (names_len + 1) * sizeof(*names));
103 names[names_len] = NULL;
104 *namesp = names;
107 int names_equal(char **a, char **b)
109 int i = 0;
110 for (; a[i] && b[i]; i++) {
111 if (strcmp(a[i], b[i])) {
112 return 0;
116 return a[i] == b[i];
119 int common_prefix_size(struct strbuf *a, struct strbuf *b)
121 int p = 0;
122 for (; p < a->len && p < b->len; p++) {
123 if (a->buf[p] != b->buf[p])
124 break;
127 return p;