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

8
#include "w32_buffer.h"
9

10 11 12 13 14 15 16 17 18 19 20 21
#include "utf-conv.h"

GIT_INLINE(int) handle_wc_error(void)
{
	if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
		errno = ENAMETOOLONG;
	else
		errno = EINVAL;

	return -1;
}

22
int git_str_put_w(git_str *buf, const wchar_t *string_w, size_t len_w)
23 24 25 26
{
	int utf8_len, utf8_write_len;
	size_t new_size;

27
	if (!len_w) {
28
		return 0;
29 30 31 32
	} else if (len_w > INT_MAX) {
		git_error_set_oom();
		return -1;
	}
33

Edward Thomson committed
34
	GIT_ASSERT(string_w);
35 36

	/* Measure the string necessary for conversion */
37
	if ((utf8_len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, string_w, (int)len_w, NULL, 0, NULL, NULL)) == 0)
38 39
		return 0;

Edward Thomson committed
40
	GIT_ASSERT(utf8_len > 0);
41

42 43
	GIT_ERROR_CHECK_ALLOC_ADD(&new_size, buf->size, (size_t)utf8_len);
	GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1);
44

45
	if (git_str_grow(buf, new_size) < 0)
46 47 48
		return -1;

	if ((utf8_write_len = WideCharToMultiByte(
49
			CP_UTF8, WC_ERR_INVALID_CHARS, string_w, (int)len_w, &buf->ptr[buf->size], utf8_len, NULL, NULL)) == 0)
50 51
		return handle_wc_error();

Edward Thomson committed
52
	GIT_ASSERT(utf8_write_len == utf8_len);
53 54 55 56 57

	buf->size += utf8_write_len;
	buf->ptr[buf->size] = '\0';
	return 0;
}