]> git.proxmox.com Git - libgit2.git/blob - src/win32/w32_buffer.c
New upstream version 1.3.0+dfsg.1
[libgit2.git] / src / win32 / w32_buffer.c
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
8 #include "w32_buffer.h"
9
10 #include "../buffer.h"
11 #include "utf-conv.h"
12
13 GIT_INLINE(int) handle_wc_error(void)
14 {
15 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
16 errno = ENAMETOOLONG;
17 else
18 errno = EINVAL;
19
20 return -1;
21 }
22
23 int git_buf_put_w(git_buf *buf, const wchar_t *string_w, size_t len_w)
24 {
25 int utf8_len, utf8_write_len;
26 size_t new_size;
27
28 if (!len_w) {
29 return 0;
30 } else if (len_w > INT_MAX) {
31 git_error_set_oom();
32 return -1;
33 }
34
35 GIT_ASSERT(string_w);
36
37 /* Measure the string necessary for conversion */
38 if ((utf8_len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, string_w, (int)len_w, NULL, 0, NULL, NULL)) == 0)
39 return 0;
40
41 GIT_ASSERT(utf8_len > 0);
42
43 GIT_ERROR_CHECK_ALLOC_ADD(&new_size, buf->size, (size_t)utf8_len);
44 GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1);
45
46 if (git_buf_grow(buf, new_size) < 0)
47 return -1;
48
49 if ((utf8_write_len = WideCharToMultiByte(
50 CP_UTF8, WC_ERR_INVALID_CHARS, string_w, (int)len_w, &buf->ptr[buf->size], utf8_len, NULL, NULL)) == 0)
51 return handle_wc_error();
52
53 GIT_ASSERT(utf8_write_len == utf8_len);
54
55 buf->size += utf8_write_len;
56 buf->ptr[buf->size] = '\0';
57 return 0;
58 }