]> git.proxmox.com Git - libgit2.git/blob - src/util.h
Merge branch 'pr/2740'
[libgit2.git] / src / util.h
1 /*
2 * Copyright (C) the libgit2 contributors. All rights reserved.
3 *
4 * This file is part of libgit2, distributed under the GNU GPL v2 with
5 * a Linking Exception. For full terms see the included COPYING file.
6 */
7 #ifndef INCLUDE_util_h__
8 #define INCLUDE_util_h__
9
10 #include "common.h"
11 #include "strnlen.h"
12
13 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
14 #define bitsizeof(x) (CHAR_BIT * sizeof(x))
15 #define MSB(x, bits) ((x) & (~0ULL << (bitsizeof(x) - (bits))))
16 #ifndef min
17 # define min(a,b) ((a) < (b) ? (a) : (b))
18 #endif
19 #ifndef max
20 # define max(a,b) ((a) > (b) ? (a) : (b))
21 #endif
22
23 #define GIT_DATE_RFC2822_SZ 32
24
25 /**
26 * Return the length of a constant string.
27 * We are aware that `strlen` performs the same task and is usually
28 * optimized away by the compiler, whilst being safer because it returns
29 * valid values when passed a pointer instead of a constant string; however
30 * this macro will transparently work with wide-char and single-char strings.
31 */
32 #define CONST_STRLEN(x) ((sizeof(x)/sizeof(x[0])) - 1)
33
34 /*
35 * Custom memory allocation wrappers
36 * that set error code and error message
37 * on allocation failure
38 */
39 GIT_INLINE(void *) git__malloc(size_t len)
40 {
41 void *ptr = malloc(len);
42 if (!ptr) giterr_set_oom();
43 return ptr;
44 }
45
46 GIT_INLINE(void *) git__calloc(size_t nelem, size_t elsize)
47 {
48 void *ptr = calloc(nelem, elsize);
49 if (!ptr) giterr_set_oom();
50 return ptr;
51 }
52
53 GIT_INLINE(char *) git__strdup(const char *str)
54 {
55 char *ptr = strdup(str);
56 if (!ptr) giterr_set_oom();
57 return ptr;
58 }
59
60 GIT_INLINE(char *) git__strndup(const char *str, size_t n)
61 {
62 size_t length = 0;
63 char *ptr;
64
65 length = p_strnlen(str, n);
66
67 ptr = (char*)git__malloc(length + 1);
68
69 if (!ptr)
70 return NULL;
71
72 if (length)
73 memcpy(ptr, str, length);
74
75 ptr[length] = '\0';
76
77 return ptr;
78 }
79
80 /* NOTE: This doesn't do null or '\0' checking. Watch those boundaries! */
81 GIT_INLINE(char *) git__substrdup(const char *start, size_t n)
82 {
83 char *ptr = (char*)git__malloc(n+1);
84 memcpy(ptr, start, n);
85 ptr[n] = '\0';
86 return ptr;
87 }
88
89 GIT_INLINE(void *) git__realloc(void *ptr, size_t size)
90 {
91 void *new_ptr = realloc(ptr, size);
92 if (!new_ptr) giterr_set_oom();
93 return new_ptr;
94 }
95
96 GIT_INLINE(void) git__free(void *ptr)
97 {
98 free(ptr);
99 }
100
101 #define STRCMP_CASESELECT(IGNORE_CASE, STR1, STR2) \
102 ((IGNORE_CASE) ? strcasecmp((STR1), (STR2)) : strcmp((STR1), (STR2)))
103
104 #define CASESELECT(IGNORE_CASE, ICASE, CASE) \
105 ((IGNORE_CASE) ? (ICASE) : (CASE))
106
107 extern int git__prefixcmp(const char *str, const char *prefix);
108 extern int git__prefixcmp_icase(const char *str, const char *prefix);
109 extern int git__prefixncmp_icase(const char *str, size_t str_n, const char *prefix);
110 extern int git__suffixcmp(const char *str, const char *suffix);
111
112 GIT_INLINE(int) git__signum(int val)
113 {
114 return ((val > 0) - (val < 0));
115 }
116
117 extern int git__strtol32(int32_t *n, const char *buff, const char **end_buf, int base);
118 extern int git__strtol64(int64_t *n, const char *buff, const char **end_buf, int base);
119
120 extern void git__hexdump(const char *buffer, size_t n);
121 extern uint32_t git__hash(const void *key, int len, uint32_t seed);
122
123 /** @return true if p fits into the range of a size_t */
124 GIT_INLINE(int) git__is_sizet(git_off_t p)
125 {
126 size_t r = (size_t)p;
127 return p == (git_off_t)r;
128 }
129
130 /** @return true if p fits into the range of a uint32_t */
131 GIT_INLINE(int) git__is_uint32(size_t p)
132 {
133 uint32_t r = (uint32_t)p;
134 return p == (size_t)r;
135 }
136
137 /** @return true if p fits into the range of an unsigned long */
138 GIT_INLINE(int) git__is_ulong(git_off_t p)
139 {
140 unsigned long r = (unsigned long)p;
141 return p == (git_off_t)r;
142 }
143
144 /* 32-bit cross-platform rotl */
145 #ifdef _MSC_VER /* use built-in method in MSVC */
146 # define git__rotl(v, s) (uint32_t)_rotl(v, s)
147 #else /* use bitops in GCC; with o2 this gets optimized to a rotl instruction */
148 # define git__rotl(v, s) (uint32_t)(((uint32_t)(v) << (s)) | ((uint32_t)(v) >> (32 - (s))))
149 #endif
150
151 extern char *git__strtok(char **end, const char *sep);
152 extern char *git__strsep(char **end, const char *sep);
153
154 extern void git__strntolower(char *str, size_t len);
155 extern void git__strtolower(char *str);
156
157 GIT_INLINE(const char *) git__next_line(const char *s)
158 {
159 while (*s && *s != '\n') s++;
160 while (*s == '\n' || *s == '\r') s++;
161 return s;
162 }
163
164 GIT_INLINE(const void *) git__memrchr(const void *s, int c, size_t n)
165 {
166 const unsigned char *cp;
167
168 if (n != 0) {
169 cp = (unsigned char *)s + n;
170 do {
171 if (*(--cp) == (unsigned char)c)
172 return cp;
173 } while (--n != 0);
174 }
175
176 return NULL;
177 }
178
179 typedef int (*git__tsort_cmp)(const void *a, const void *b);
180
181 extern void git__tsort(void **dst, size_t size, git__tsort_cmp cmp);
182
183 typedef int (*git__sort_r_cmp)(const void *a, const void *b, void *payload);
184
185 extern void git__tsort_r(
186 void **dst, size_t size, git__sort_r_cmp cmp, void *payload);
187
188 extern void git__qsort_r(
189 void *els, size_t nel, size_t elsize, git__sort_r_cmp cmp, void *payload);
190
191 extern void git__insertsort_r(
192 void *els, size_t nel, size_t elsize, void *swapel,
193 git__sort_r_cmp cmp, void *payload);
194
195 /**
196 * @param position If non-NULL, this will be set to the position where the
197 * element is or would be inserted if not found.
198 * @return 0 if found; GIT_ENOTFOUND if not found
199 */
200 extern int git__bsearch(
201 void **array,
202 size_t array_len,
203 const void *key,
204 int (*compare)(const void *key, const void *element),
205 size_t *position);
206
207 extern int git__bsearch_r(
208 void **array,
209 size_t array_len,
210 const void *key,
211 int (*compare_r)(const void *key, const void *element, void *payload),
212 void *payload,
213 size_t *position);
214
215 extern int git__strcmp_cb(const void *a, const void *b);
216 extern int git__strcasecmp_cb(const void *a, const void *b);
217
218 extern int git__strcmp(const char *a, const char *b);
219 extern int git__strcasecmp(const char *a, const char *b);
220 extern int git__strncmp(const char *a, const char *b, size_t sz);
221 extern int git__strncasecmp(const char *a, const char *b, size_t sz);
222
223 extern int git__strcasesort_cmp(const char *a, const char *b);
224
225 #include "thread-utils.h"
226
227 typedef struct {
228 git_atomic refcount;
229 void *owner;
230 } git_refcount;
231
232 typedef void (*git_refcount_freeptr)(void *r);
233
234 #define GIT_REFCOUNT_INC(r) { \
235 git_atomic_inc(&((git_refcount *)(r))->refcount); \
236 }
237
238 #define GIT_REFCOUNT_DEC(_r, do_free) { \
239 git_refcount *r = (git_refcount *)(_r); \
240 int val = git_atomic_dec(&r->refcount); \
241 if (val <= 0 && r->owner == NULL) { do_free(_r); } \
242 }
243
244 #define GIT_REFCOUNT_OWN(r, o) { \
245 ((git_refcount *)(r))->owner = o; \
246 }
247
248 #define GIT_REFCOUNT_OWNER(r) (((git_refcount *)(r))->owner)
249
250 #define GIT_REFCOUNT_VAL(r) git_atomic_get(&((git_refcount *)(r))->refcount)
251
252
253 static signed char from_hex[] = {
254 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 00 */
255 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10 */
256 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20 */
257 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, /* 30 */
258 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 40 */
259 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 50 */
260 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 60 */
261 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 70 */
262 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 80 */
263 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 90 */
264 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* a0 */
265 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* b0 */
266 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* c0 */
267 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* d0 */
268 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* e0 */
269 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* f0 */
270 };
271
272 GIT_INLINE(int) git__fromhex(char h)
273 {
274 return from_hex[(unsigned char) h];
275 }
276
277 GIT_INLINE(int) git__ishex(const char *str)
278 {
279 unsigned i;
280 for (i=0; i<strlen(str); i++)
281 if (git__fromhex(str[i]) < 0)
282 return 0;
283 return 1;
284 }
285
286 GIT_INLINE(size_t) git__size_t_bitmask(size_t v)
287 {
288 v--;
289 v |= v >> 1;
290 v |= v >> 2;
291 v |= v >> 4;
292 v |= v >> 8;
293 v |= v >> 16;
294
295 return v;
296 }
297
298 GIT_INLINE(size_t) git__size_t_powerof2(size_t v)
299 {
300 return git__size_t_bitmask(v) + 1;
301 }
302
303 GIT_INLINE(bool) git__isupper(int c)
304 {
305 return (c >= 'A' && c <= 'Z');
306 }
307
308 GIT_INLINE(bool) git__isalpha(int c)
309 {
310 return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));
311 }
312
313 GIT_INLINE(bool) git__isdigit(int c)
314 {
315 return (c >= '0' && c <= '9');
316 }
317
318 GIT_INLINE(bool) git__isspace(int c)
319 {
320 return (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == '\v');
321 }
322
323 GIT_INLINE(bool) git__isspace_nonlf(int c)
324 {
325 return (c == ' ' || c == '\t' || c == '\f' || c == '\r' || c == '\v');
326 }
327
328 GIT_INLINE(bool) git__iswildcard(int c)
329 {
330 return (c == '*' || c == '?' || c == '[');
331 }
332
333 /*
334 * Parse a string value as a boolean, just like Core Git does.
335 *
336 * Valid values for true are: 'true', 'yes', 'on'
337 * Valid values for false are: 'false', 'no', 'off'
338 */
339 extern int git__parse_bool(int *out, const char *value);
340
341 /*
342 * Parse a string into a value as a git_time_t.
343 *
344 * Sample valid input:
345 * - "yesterday"
346 * - "July 17, 2003"
347 * - "2003-7-17 08:23"
348 */
349 extern int git__date_parse(git_time_t *out, const char *date);
350
351 /*
352 * Format a git_time as a RFC2822 string
353 *
354 * @param out buffer to store formatted date; a '\\0' terminator will automatically be added.
355 * @param len size of the buffer; should be atleast `GIT_DATE_RFC2822_SZ` in size;
356 * @param date the date to be formatted
357 * @return 0 if successful; -1 on error
358 */
359 extern int git__date_rfc2822_fmt(char *out, size_t len, const git_time *date);
360
361 /*
362 * Unescapes a string in-place.
363 *
364 * Edge cases behavior:
365 * - "jackie\" -> "jacky\"
366 * - "chan\\" -> "chan\"
367 */
368 extern size_t git__unescape(char *str);
369
370 /*
371 * Iterate through an UTF-8 string, yielding one
372 * codepoint at a time.
373 *
374 * @param str current position in the string
375 * @param str_len size left in the string; -1 if the string is NULL-terminated
376 * @param dst pointer where to store the current codepoint
377 * @return length in bytes of the read codepoint; -1 if the codepoint was invalid
378 */
379 extern int git__utf8_iterate(const uint8_t *str, int str_len, int32_t *dst);
380
381 /*
382 * Safely zero-out memory, making sure that the compiler
383 * doesn't optimize away the operation.
384 */
385 GIT_INLINE(void) git__memzero(void *data, size_t size)
386 {
387 #ifdef _MSC_VER
388 SecureZeroMemory((PVOID)data, size);
389 #else
390 volatile uint8_t *scan = (volatile uint8_t *)data;
391
392 while (size--)
393 *scan++ = 0x0;
394 #endif
395 }
396
397 #ifdef GIT_WIN32
398
399 GIT_INLINE(double) git__timer(void)
400 {
401 /* We need the initial tick count to detect if the tick
402 * count has rolled over. */
403 static DWORD initial_tick_count = 0;
404
405 /* GetTickCount returns the number of milliseconds that have
406 * elapsed since the system was started. */
407 DWORD count = GetTickCount();
408
409 if(initial_tick_count == 0) {
410 initial_tick_count = count;
411 } else if (count < initial_tick_count) {
412 /* The tick count has rolled over - adjust for it. */
413 count = (0xFFFFFFFF - initial_tick_count) + count;
414 }
415
416 return (double) count / (double) 1000;
417 }
418
419 #elif __APPLE__
420
421 #include <mach/mach_time.h>
422
423 GIT_INLINE(double) git__timer(void)
424 {
425 uint64_t time = mach_absolute_time();
426 static double scaling_factor = 0;
427
428 if (scaling_factor == 0) {
429 mach_timebase_info_data_t info;
430 (void)mach_timebase_info(&info);
431 scaling_factor = (double)info.numer / (double)info.denom;
432 }
433
434 return (double)time * scaling_factor / 1.0E9;
435 }
436
437 #elif defined(AMIGA)
438
439 #include <proto/timer.h>
440
441 GIT_INLINE(double) git__timer(void)
442 {
443 struct TimeVal tv;
444 ITimer->GetUpTime(&tv);
445 return (double)tv.Seconds + (double)tv.Microseconds / 1.0E6;
446 }
447
448 #else
449
450 #include <sys/time.h>
451
452 GIT_INLINE(double) git__timer(void)
453 {
454 struct timespec tp;
455
456 if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0) {
457 return (double) tp.tv_sec + (double) tp.tv_nsec / 1.0E9;
458 } else {
459 /* Fall back to using gettimeofday */
460 struct timeval tv;
461 struct timezone tz;
462 gettimeofday(&tv, &tz);
463 return (double)tv.tv_sec + (double)tv.tv_usec / 1.0E6;
464 }
465 }
466
467 #endif
468
469 #endif /* INCLUDE_util_h__ */