Merge branch 'jk/http-leakfixes' into ps/leakfixes-part-8
[git/gitster.git] / reftable / basics.c
blob0058619ca6742ae29b4f50d7188b0fc19d87f45b
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 size_t 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;
42 int ret = f(mid, args);
43 if (ret < 0)
44 return sz;
46 if (ret > 0)
47 hi = mid;
48 else
49 lo = mid;
52 if (lo)
53 return hi;
55 return f(0, args) ? 0 : 1;
58 void free_names(char **a)
60 char **p;
61 if (!a) {
62 return;
64 for (p = a; *p; p++) {
65 reftable_free(*p);
67 reftable_free(a);
70 size_t names_length(const char **names)
72 const char **p = names;
73 while (*p)
74 p++;
75 return p - names;
78 void parse_names(char *buf, int size, char ***namesp)
80 char **names = NULL;
81 size_t names_cap = 0;
82 size_t names_len = 0;
84 char *p = buf;
85 char *end = buf + size;
86 while (p < end) {
87 char *next = strchr(p, '\n');
88 if (next && next < end) {
89 *next = 0;
90 } else {
91 next = end;
93 if (p < next) {
94 REFTABLE_ALLOC_GROW(names, names_len + 1, names_cap);
95 names[names_len++] = xstrdup(p);
97 p = next + 1;
100 REFTABLE_REALLOC_ARRAY(names, names_len + 1);
101 names[names_len] = NULL;
102 *namesp = names;
105 int names_equal(const char **a, const char **b)
107 size_t i = 0;
108 for (; a[i] && b[i]; i++)
109 if (strcmp(a[i], b[i]))
110 return 0;
111 return a[i] == b[i];
114 int common_prefix_size(struct strbuf *a, struct strbuf *b)
116 int p = 0;
117 for (; p < a->len && p < b->len; p++) {
118 if (a->buf[p] != b->buf[p])
119 break;
122 return p;