util.c 18.4 KB
Newer Older
Vicent Marti committed
1
/*
Edward Thomson committed
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
Vicent Marti committed
3 4 5 6
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */
7 8 9

#include "util.h"

10
#include "common.h"
11

12
#ifdef GIT_WIN32
13
# include "win32/utf-conv.h"
14
# include "win32/w32_buffer.h"
15 16 17 18

# ifdef HAVE_QSORT_S
#  include <search.h>
# endif
19 20
#endif

21
#ifdef _MSC_VER
22 23 24
# include <Shlwapi.h>
#endif

25 26 27
void git_strarray_free(git_strarray *array)
{
	size_t i;
28 29 30 31

	if (array == NULL)
		return;

32
	for (i = 0; i < array->count; ++i)
33
		git__free(array->strings[i]);
34

35
	git__free(array->strings);
36 37

	memset(array, 0, sizeof(*array));
38 39
}

40 41 42 43
int git_strarray_copy(git_strarray *tgt, const git_strarray *src)
{
	size_t i;

Russell Belfer committed
44
	assert(tgt && src);
45 46 47

	memset(tgt, 0, sizeof(*tgt));

Russell Belfer committed
48
	if (!src->count)
49 50
		return 0;

Russell Belfer committed
51
	tgt->strings = git__calloc(src->count, sizeof(char *));
52 53
	GITERR_CHECK_ALLOC(tgt->strings);

Russell Belfer committed
54 55
	for (i = 0; i < src->count; ++i) {
		if (!src->strings[i])
56
			continue;
57

Russell Belfer committed
58
		tgt->strings[tgt->count] = git__strdup(src->strings[i]);
59 60
		if (!tgt->strings[tgt->count]) {
			git_strarray_free(tgt);
Russell Belfer committed
61
			memset(tgt, 0, sizeof(*tgt));
62 63 64 65 66 67 68 69 70
			return -1;
		}

		tgt->count++;
	}

	return 0;
}

71
int git__strtol64(int64_t *result, const char *nptr, const char **endptr, int base)
72
{
73 74 75 76 77 78

	return git__strntol64(result, nptr, (size_t)-1, endptr, base);
}

int git__strntol64(int64_t *result, const char *nptr, size_t nptr_len, const char **endptr, int base)
{
79
	const char *p;
80
	int64_t n, nn;
81 82 83 84 85 86 87 88 89 90 91
	int c, ovfl, v, neg, ndig;

	p = nptr;
	neg = 0;
	n = 0;
	ndig = 0;
	ovfl = 0;

	/*
	 * White space
	 */
92
	while (git__isspace(*p))
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
		p++;

	/*
	 * Sign
	 */
	if (*p == '-' || *p == '+')
		if (*p++ == '-')
			neg = 1;

	/*
	 * Base
	 */
	if (base == 0) {
		if (*p != '0')
			base = 10;
		else {
			base = 8;
			if (p[1] == 'x' || p[1] == 'X') {
				p += 2;
				base = 16;
			}
		}
	} else if (base == 16 && *p == '0') {
		if (p[1] == 'x' || p[1] == 'X')
			p += 2;
	} else if (base < 0 || 36 < base)
		goto Return;

	/*
	 * Non-empty sequence of digits
	 */
124
	for (; nptr_len > 0; p++,ndig++,nptr_len--) {
125 126 127 128 129 130 131 132 133 134
		c = *p;
		v = base;
		if ('0'<=c && c<='9')
			v = c - '0';
		else if ('a'<=c && c<='z')
			v = c - 'a' + 10;
		else if ('A'<=c && c<='Z')
			v = c - 'A' + 10;
		if (v >= base)
			break;
135 136
		nn = n * base + (neg ? -v : v);
		if ((!neg && nn < n) || (neg && nn > n))
137 138 139 140 141
			ovfl = 1;
		n = nn;
	}

Return:
142
	if (ndig == 0) {
143
		giterr_set(GITERR_INVALID, "failed to convert string to long: not a number");
144 145
		return -1;
	}
146 147 148 149

	if (endptr)
		*endptr = p;

150
	if (ovfl) {
151
		giterr_set(GITERR_INVALID, "failed to convert string to long: overflow error");
152 153
		return -1;
	}
154

155
	*result = n;
156
	return 0;
157 158
}

159
int git__strtol32(int32_t *result, const char *nptr, const char **endptr, int base)
160
{
161 162 163 164 165 166

	return git__strntol32(result, nptr, (size_t)-1, endptr, base);
}

int git__strntol32(int32_t *result, const char *nptr, size_t nptr_len, const char **endptr, int base)
{
167
	int error;
168 169
	int32_t tmp_int;
	int64_t tmp_long;
170

171
	if ((error = git__strntol64(&tmp_long, nptr, nptr_len, endptr, base)) < 0)
172 173 174
		return error;

	tmp_int = tmp_long & 0xFFFFFFFF;
175
	if (tmp_int != tmp_long) {
176
		giterr_set(GITERR_INVALID, "failed to convert: '%s' is too large", nptr);
177 178
		return -1;
	}
179 180

	*result = tmp_int;
181

182 183 184
	return error;
}

185 186 187 188 189 190 191 192 193
int git__strcmp(const char *a, const char *b)
{
	while (*a && *b && *a == *b)
		++a, ++b;
	return (int)(*(const unsigned char *)a) - (int)(*(const unsigned char *)b);
}

int git__strcasecmp(const char *a, const char *b)
{
194
	while (*a && *b && git__tolower(*a) == git__tolower(*b))
195
		++a, ++b;
196
	return ((unsigned char)git__tolower(*a) - (unsigned char)git__tolower(*b));
197 198
}

199 200 201 202 203
int git__strcasesort_cmp(const char *a, const char *b)
{
	int cmp = 0;

	while (*a && *b) {
Russell Belfer committed
204
		if (*a != *b) {
205
			if (git__tolower(*a) != git__tolower(*b))
Russell Belfer committed
206 207
				break;
			/* use case in sort order even if not in equivalence */
208
			if (!cmp)
Russell Belfer committed
209 210
				cmp = (int)(*(const uint8_t *)a) - (int)(*(const uint8_t *)b);
		}
211 212 213 214 215

		++a, ++b;
	}

	if (*a || *b)
216
		return (unsigned char)git__tolower(*a) - (unsigned char)git__tolower(*b);
217 218 219 220

	return cmp;
}

221 222 223 224 225 226 227 228 229 230 231
int git__strncmp(const char *a, const char *b, size_t sz)
{
	while (sz && *a && *b && *a == *b)
		--sz, ++a, ++b;
	if (!sz)
		return 0;
	return (int)(*(const unsigned char *)a) - (int)(*(const unsigned char *)b);
}

int git__strncasecmp(const char *a, const char *b, size_t sz)
{
Philip Kelley committed
232
	int al, bl;
233

Philip Kelley committed
234
	do {
235 236
		al = (unsigned char)git__tolower(*a);
		bl = (unsigned char)git__tolower(*b);
Philip Kelley committed
237 238
		++a, ++b;
	} while (--sz && al && al == bl);
239

Philip Kelley committed
240
	return al - bl;
241 242
}

243
void git__strntolower(char *str, size_t len)
244
{
245
	size_t i;
246 247

	for (i = 0; i < len; ++i) {
248
		str[i] = (char)git__tolower(str[i]);
249 250 251 252 253 254 255 256
	}
}

void git__strtolower(char *str)
{
	git__strntolower(str, strlen(str));
}

257
GIT_INLINE(int) prefixcmp(const char *str, size_t str_n, const char *prefix, bool icase)
258
{
259 260 261 262 263 264 265 266 267 268 269
	int s, p;

	while (str_n--) {
		s = (unsigned char)*str++;
		p = (unsigned char)*prefix++;

		if (icase) {
			s = git__tolower(s);
			p = git__tolower(p);
		}

270 271
		if (!p)
			return 0;
272 273

		if (s != p)
274 275
			return s - p;
	}
276 277

	return (0 - *prefix);
278 279
}

280
int git__prefixcmp(const char *str, const char *prefix)
281
{
282
	return prefixcmp(str, SIZE_MAX, prefix, false);
283 284
}

285
int git__prefixncmp(const char *str, size_t str_n, const char *prefix)
286
{
287 288
	return prefixcmp(str, str_n, prefix, false);
}
289

290 291 292 293
int git__prefixcmp_icase(const char *str, const char *prefix)
{
	return prefixcmp(str, SIZE_MAX, prefix, true);
}
294

295 296 297
int git__prefixncmp_icase(const char *str, size_t str_n, const char *prefix)
{
	return prefixcmp(str, str_n, prefix, true);
298 299
}

300 301 302 303 304 305 306 307
int git__suffixcmp(const char *str, const char *suffix)
{
	size_t a = strlen(str);
	size_t b = strlen(suffix);
	if (a < b)
		return -1;
	return strcmp(str + (a - b), suffix);
}
308

309
char *git__strtok(char **end, const char *sep)
310
{
311
	char *ptr = *end;
312

313 314
	while (*ptr && strchr(sep, *ptr))
		++ptr;
315

316 317 318
	if (*ptr) {
		char *start = ptr;
		*end = start + 1;
319

320 321
		while (**end && !strchr(sep, **end))
			++*end;
322

323 324 325 326 327 328 329 330 331
		if (**end) {
			**end = '\0';
			++*end;
		}

		return start;
	}

	return NULL;
332 333
}

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
/* Similar to strtok, but does not collapse repeated tokens. */
char *git__strsep(char **end, const char *sep)
{
	char *start = *end, *ptr = *end;

	while (*ptr && !strchr(sep, *ptr))
		++ptr;

	if (*ptr) {
		*end = ptr + 1;
		*ptr = '\0';

		return start;
	}

	return NULL;
}

352 353 354 355 356 357
size_t git__linenlen(const char *buffer, size_t buffer_len)
{
	char *nl = memchr(buffer, '\n', buffer_len);
	return nl ? (size_t)(nl - buffer) + 1 : buffer_len;
}

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
void git__hexdump(const char *buffer, size_t len)
{
	static const size_t LINE_WIDTH = 16;

	size_t line_count, last_line, i, j;
	const char *line;

	line_count = (len / LINE_WIDTH);
	last_line = (len % LINE_WIDTH);

	for (i = 0; i < line_count; ++i) {
		line = buffer + (i * LINE_WIDTH);
		for (j = 0; j < LINE_WIDTH; ++j, ++line)
			printf("%02X ", (unsigned char)*line & 0xFF);

		printf("| ");

		line = buffer + (i * LINE_WIDTH);
		for (j = 0; j < LINE_WIDTH; ++j, ++line)
			printf("%c", (*line >= 32 && *line <= 126) ? *line : '.');

		printf("\n");
	}

	if (last_line > 0) {

		line = buffer + (line_count * LINE_WIDTH);
		for (j = 0; j < last_line; ++j, ++line)
			printf("%02X ", (unsigned char)*line & 0xFF);

		for (j = 0; j < (LINE_WIDTH - last_line); ++j)
Vicent Marti committed
389
			printf("	");
390 391 392 393 394 395 396 397 398 399 400 401

		printf("| ");

		line = buffer + (line_count * LINE_WIDTH);
		for (j = 0; j < last_line; ++j, ++line)
			printf("%c", (*line >= 32 && *line <= 126) ? *line : '.');

		printf("\n");
	}

	printf("\n");
}
402 403 404 405 406 407 408 409 410 411 412 413 414

#ifdef GIT_LEGACY_HASH
uint32_t git__hash(const void *key, int len, unsigned int seed)
{
	const uint32_t m = 0x5bd1e995;
	const int r = 24;
	uint32_t h = seed ^ len;

	const unsigned char *data = (const unsigned char *)key;

	while(len >= 4) {
		uint32_t k = *(uint32_t *)data;

415 416 417 418 419
		k *= m;
		k ^= k >> r;
		k *= m;

		h *= m;
420 421 422 423 424
		h ^= k;

		data += 4;
		len -= 4;
	}
425

426 427 428 429
	switch(len) {
	case 3: h ^= data[2] << 16;
	case 2: h ^= data[1] << 8;
	case 1: h ^= data[0];
Vicent Marti committed
430
			h *= m;
431 432 433 434 435 436 437
	};

	h ^= h >> 13;
	h *= m;
	h ^= h >> 15;

	return h;
438
}
439 440 441 442 443 444 445 446 447 448 449 450
#else
/*
	Cross-platform version of Murmurhash3
	http://code.google.com/p/smhasher/wiki/MurmurHash3
	by Austin Appleby (aappleby@gmail.com)

	This code is on the public domain.
*/
uint32_t git__hash(const void *key, int len, uint32_t seed)
{

#define MURMUR_BLOCK() {\
Vicent Marti committed
451 452 453 454 455 456 457
	k1 *= c1; \
	k1 = git__rotl(k1,11);\
	k1 *= c2;\
	h1 ^= k1;\
	h1 = h1*3 + 0x52dce729;\
	c1 = c1*5 + 0x7b7d159c;\
	c2 = c2*5 + 0x6bce6396;\
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
}

	const uint8_t *data = (const uint8_t*)key;
	const int nblocks = len / 4;

	const uint32_t *blocks = (const uint32_t *)(data + nblocks * 4);
	const uint8_t *tail = (const uint8_t *)(data + nblocks * 4);

	uint32_t h1 = 0x971e137b ^ seed;
	uint32_t k1;

	uint32_t c1 = 0x95543787;
	uint32_t c2 = 0x2ad7eb25;

	int i;

	for (i = -nblocks; i; i++) {
		k1 = blocks[i];
		MURMUR_BLOCK();
	}

	k1 = 0;

	switch(len & 3) {
	case 3: k1 ^= tail[2] << 16;
483
		/* fall through */
484
	case 2: k1 ^= tail[1] << 8;
485
		/* fall through */
486
	case 1: k1 ^= tail[0];
487
		MURMUR_BLOCK();
488 489 490 491 492 493 494 495 496 497
	}

	h1 ^= len;
	h1 ^= h1 >> 16;
	h1 *= 0x85ebca6b;
	h1 ^= h1 >> 13;
	h1 *= 0xc2b2ae35;
	h1 ^= h1 >> 16;

	return h1;
498
}
499
#endif
500

501 502 503 504 505
/**
 * A modified `bsearch` from the BSD glibc.
 *
 * Copyright (c) 1990 Regents of the University of California.
 * All rights reserved.
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 3. [rescinded 22 July 1999]
 * 4. Neither the name of the University nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
530
 */
531 532 533 534 535 536
int git__bsearch(
	void **array,
	size_t array_len,
	const void *key,
	int (*compare)(const void *, const void *),
	size_t *position)
537
{
538
	size_t lim;
539
	int cmp = -1;
540 541
	void **part, **base = array;

542
	for (lim = array_len; lim != 0; lim >>= 1) {
543 544 545
		part = base + (lim >> 1);
		cmp = (*compare)(key, *part);
		if (cmp == 0) {
546 547 548 549
			base = part;
			break;
		}
		if (cmp > 0) { /* key > p; take right partition */
550 551 552 553 554
			base = part + 1;
			lim--;
		} /* else take left partition */
	}

555 556
	if (position)
		*position = (base - array);
557

558
	return (cmp == 0) ? 0 : GIT_ENOTFOUND;
559 560 561 562 563 564 565 566 567 568
}

int git__bsearch_r(
	void **array,
	size_t array_len,
	const void *key,
	int (*compare_r)(const void *, const void *, void *),
	void *payload,
	size_t *position)
{
569
	size_t lim;
570 571 572
	int cmp = -1;
	void **part, **base = array;

573
	for (lim = array_len; lim != 0; lim >>= 1) {
574 575 576 577 578 579 580 581 582 583 584 585 586 587
		part = base + (lim >> 1);
		cmp = (*compare_r)(key, *part, payload);
		if (cmp == 0) {
			base = part;
			break;
		}
		if (cmp > 0) { /* key > p; take right partition */
			base = part + 1;
			lim--;
		} /* else take left partition */
	}

	if (position)
		*position = (base - array);
588

589
	return (cmp == 0) ? 0 : GIT_ENOTFOUND;
590 591
}

592 593
/**
 * A strcmp wrapper
594
 *
595 596 597 598 599
 * We don't want direct pointers to the CRT on Windows, we may
 * get stdcall conflicts.
 */
int git__strcmp_cb(const void *a, const void *b)
{
600 601
	return strcmp((const char *)a, (const char *)b);
}
602

603 604 605
int git__strcasecmp_cb(const void *a, const void *b)
{
	return strcasecmp((const char *)a, (const char *)b);
606
}
607 608 609 610

int git__parse_bool(int *out, const char *value)
{
	/* A missing value means true */
611 612
	if (value == NULL ||
		!strcasecmp(value, "true") ||
613 614 615 616 617 618 619
		!strcasecmp(value, "yes") ||
		!strcasecmp(value, "on")) {
		*out = 1;
		return 0;
	}
	if (!strcasecmp(value, "false") ||
		!strcasecmp(value, "no") ||
620 621
		!strcasecmp(value, "off") ||
		value[0] == '\0') {
622 623 624 625 626 627
		*out = 0;
		return 0;
	}

	return -1;
}
628 629 630 631 632

size_t git__unescape(char *str)
{
	char *scan, *pos = str;

633 634 635
	if (!str)
		return 0;

636 637 638 639 640 641 642 643 644 645 646 647 648
	for (scan = str; *scan; pos++, scan++) {
		if (*scan == '\\' && *(scan + 1) != '\0')
			scan++; /* skip '\' but include next char */
		if (pos != scan)
			*pos = *scan;
	}

	if (pos != scan) {
		*pos = '\0';
	}

	return (pos - str);
}
649

650
#if defined(HAVE_QSORT_S) || (defined(HAVE_QSORT_R) && defined(BSD))
651
typedef struct {
652
	git__sort_r_cmp cmp;
653 654 655 656 657 658 659 660 661 662 663 664
	void *payload;
} git__qsort_r_glue;

static int GIT_STDLIB_CALL git__qsort_r_glue_cmp(
	void *payload, const void *a, const void *b)
{
	git__qsort_r_glue *glue = payload;
	return glue->cmp(a, b, glue->payload);
}
#endif

void git__qsort_r(
665
	void *els, size_t nel, size_t elsize, git__sort_r_cmp cmp, void *payload)
666
{
667
#if defined(HAVE_QSORT_R) && defined(BSD)
668 669
	git__qsort_r_glue glue = { cmp, payload };
	qsort_r(els, nel, elsize, &glue, git__qsort_r_glue_cmp);
670
#elif defined(HAVE_QSORT_R) && defined(__GLIBC__)
671
	qsort_r(els, nel, elsize, cmp, payload);
672 673 674 675 676
#elif defined(HAVE_QSORT_S)
	git__qsort_r_glue glue = { cmp, payload };
	qsort_s(els, nel, elsize, git__qsort_r_glue_cmp, &glue);
#else
	git__insertsort_r(els, nel, elsize, NULL, cmp, payload);
677
#endif
678 679 680 681 682 683
}

void git__insertsort_r(
	void *els, size_t nel, size_t elsize, void *swapel,
	git__sort_r_cmp cmp, void *payload)
{
684 685
	uint8_t *base = els;
	uint8_t *end = base + nel * elsize;
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
	uint8_t *i, *j;
	bool freeswap = !swapel;

	if (freeswap)
		swapel = git__malloc(elsize);

	for (i = base + elsize; i < end; i += elsize)
		for (j = i; j > base && cmp(j, j - elsize, payload) < 0; j -= elsize) {
			memcpy(swapel, j, elsize);
			memcpy(j, j - elsize, elsize);
			memcpy(j - elsize, swapel, elsize);
		}

	if (freeswap)
		git__free(swapel);
701
}
702

703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
/*
 * git__utf8_iterate is taken from the utf8proc project,
 * http://www.public-software-group.org/utf8proc
 *
 * Copyright (c) 2009 Public Software Group e. V., Berlin, Germany
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the ""Software""),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
static const int8_t utf8proc_utf8class[256] = {
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
	2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
	3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
	4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0
};

int git__utf8_charlen(const uint8_t *str, int str_len)
{
	int length, i;

	length = utf8proc_utf8class[str[0]];
	if (!length)
		return -1;

	if (str_len >= 0 && length > str_len)
		return -str_len;

	for (i = 1; i < length; i++) {
		if ((str[i] & 0xC0) != 0x80)
			return -i;
	}

	return length;
}

int git__utf8_iterate(const uint8_t *str, int str_len, int32_t *dst)
{
	int length;
	int32_t uc = -1;

	*dst = -1;
	length = git__utf8_charlen(str, str_len);
	if (length < 0)
		return -1;

	switch (length) {
		case 1:
			uc = str[0];
			break;
		case 2:
			uc = ((str[0] & 0x1F) <<  6) + (str[1] & 0x3F);
			if (uc < 0x80) uc = -1;
			break;
		case 3:
			uc = ((str[0] & 0x0F) << 12) + ((str[1] & 0x3F) <<  6)
				+ (str[2] & 0x3F);
			if (uc < 0x800 || (uc >= 0xD800 && uc < 0xE000) ||
					(uc >= 0xFDD0 && uc < 0xFDF0)) uc = -1;
			break;
		case 4:
			uc = ((str[0] & 0x07) << 18) + ((str[1] & 0x3F) << 12)
				+ ((str[2] & 0x3F) <<  6) + (str[3] & 0x3F);
			if (uc < 0x10000 || uc >= 0x110000) uc = -1;
			break;
	}

	if (uc < 0 || ((uc & 0xFFFF) >= 0xFFFE))
		return -1;

	*dst = uc;
	return length;
}
803

804 805 806 807 808
double git_time_monotonic(void)
{
	return git__timer();
}

809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
size_t git__utf8_valid_buf_length(const uint8_t *str, size_t str_len)
{
	size_t offset = 0;

	while (offset < str_len) {
		int length = git__utf8_charlen(str + offset, str_len - offset);

		if (length < 0)
			break;

		offset += length;
	}

	return offset;
}

825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
#ifdef GIT_WIN32
int git__getenv(git_buf *out, const char *name)
{
	wchar_t *wide_name = NULL, *wide_value = NULL;
	DWORD value_len;
	int error = -1;

	git_buf_clear(out);

	if (git__utf8_to_16_alloc(&wide_name, name) < 0)
		return -1;

	if ((value_len = GetEnvironmentVariableW(wide_name, NULL, 0)) > 0) {
		wide_value = git__malloc(value_len * sizeof(wchar_t));
		GITERR_CHECK_ALLOC(wide_value);

		value_len = GetEnvironmentVariableW(wide_name, wide_value, value_len);
	}

	if (value_len)
		error = git_buf_put_w(out, wide_value, value_len);
	else if (GetLastError() == ERROR_ENVVAR_NOT_FOUND)
		error = GIT_ENOTFOUND;
	else
		giterr_set(GITERR_OS, "could not read environment variable '%s'", name);

	git__free(wide_name);
	git__free(wide_value);
	return error;
}
#else
int git__getenv(git_buf *out, const char *name)
{
	const char *val = getenv(name);

	git_buf_clear(out);

	if (!val)
		return GIT_ENOTFOUND;

	return git_buf_puts(out, val);
}
#endif