]> git.proxmox.com Git - libgit2.git/blob - src/win32/utf-conv.c
Merge remote-tracking branch 'scottjg/fix-mingw32' into development
[libgit2.git] / src / win32 / utf-conv.c
1 /*
2 * Copyright (C) 2009-2012 the libgit2 contributors
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 "common.h"
9 #include "utf-conv.h"
10 #include "git2/windows.h"
11
12 /*
13 * Default codepage value
14 */
15 static int _active_codepage = CP_UTF8;
16
17 void gitwin_set_codepage(unsigned int codepage)
18 {
19 _active_codepage = codepage;
20 }
21
22 unsigned int gitwin_get_codepage(void)
23 {
24 return _active_codepage;
25 }
26
27 void gitwin_set_utf8(void)
28 {
29 _active_codepage = CP_UTF8;
30 }
31
32 wchar_t* gitwin_to_utf16(const char* str)
33 {
34 wchar_t* ret;
35 size_t cb;
36
37 if (!str)
38 return NULL;
39
40 cb = strlen(str) * sizeof(wchar_t);
41 if (cb == 0)
42 return (wchar_t *)git__calloc(1, sizeof(wchar_t));
43
44 /* Add space for null terminator */
45 cb += sizeof(wchar_t);
46
47 ret = (wchar_t *)git__malloc(cb);
48 if (!ret)
49 return NULL;
50
51 if (MultiByteToWideChar(_active_codepage, 0, str, -1, ret, (int)cb) == 0) {
52 giterr_set(GITERR_OS, "Could not convert string to UTF-16");
53 git__free(ret);
54 ret = NULL;
55 }
56
57 return ret;
58 }
59
60 int gitwin_append_utf16(wchar_t *buffer, const char *str, size_t len)
61 {
62 int result = MultiByteToWideChar(_active_codepage, 0, str, -1, buffer, (int)len);
63 if (result == 0)
64 giterr_set(GITERR_OS, "Could not convert string to UTF-16");
65 return result;
66 }
67
68 char* gitwin_from_utf16(const wchar_t* str)
69 {
70 char* ret;
71 size_t cb;
72
73 if (!str)
74 return NULL;
75
76 cb = wcslen(str) * sizeof(char);
77 if (cb == 0)
78 return (char *)git__calloc(1, sizeof(char));
79
80 /* Add space for null terminator */
81 cb += sizeof(char);
82
83 ret = (char*)git__malloc(cb);
84 if (!ret)
85 return NULL;
86
87 if (WideCharToMultiByte(_active_codepage, 0, str, -1, ret, (int)cb, NULL, NULL) == 0) {
88 giterr_set(GITERR_OS, "Could not convert string to UTF-8");
89 git__free(ret);
90 ret = NULL;
91 }
92
93 return ret;
94
95 }