Hash :
9e35d7fd
Author :
Date :
2012-05-24T13:44:24
Fix bugs in UTF-8 <-> UTF-16 conversion The function to convert UTF-16 to UTF-8 was only allocating a buffer of wcslen(utf16str) bytes for the UTF-8 string, but that is not sufficient if you have multibyte characters, and so when those occured, the conversion was failing. This updates the conversion functions to use the Win APIs to calculate the correct buffer lengths. Also fixes a comparison in the unit tests that would fail if you did not have a particular environment variable set.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
/*
* Copyright (C) 2009-2012 the libgit2 contributors
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "utf-conv.h"
#include "git2/windows.h"
/*
* Default codepage value
*/
static int _active_codepage = CP_UTF8;
void gitwin_set_codepage(unsigned int codepage)
{
_active_codepage = codepage;
}
unsigned int gitwin_get_codepage(void)
{
return _active_codepage;
}
void gitwin_set_utf8(void)
{
_active_codepage = CP_UTF8;
}
wchar_t* gitwin_to_utf16(const char* str)
{
wchar_t* ret;
int cb;
if (!str)
return NULL;
cb = MultiByteToWideChar(_active_codepage, 0, str, -1, NULL, 0);
if (cb == 0)
return (wchar_t *)git__calloc(1, sizeof(wchar_t));
ret = (wchar_t *)git__malloc(cb * sizeof(wchar_t));
if (!ret)
return NULL;
if (MultiByteToWideChar(_active_codepage, 0, str, -1, ret, (int)cb) == 0) {
giterr_set(GITERR_OS, "Could not convert string to UTF-16");
git__free(ret);
ret = NULL;
}
return ret;
}
int gitwin_append_utf16(wchar_t *buffer, const char *str, size_t len)
{
int result = MultiByteToWideChar(
_active_codepage, 0, str, -1, buffer, (int)len);
if (result == 0)
giterr_set(GITERR_OS, "Could not convert string to UTF-16");
return result;
}
char* gitwin_from_utf16(const wchar_t* str)
{
char* ret;
int cb;
if (!str)
return NULL;
cb = WideCharToMultiByte(_active_codepage, 0, str, -1, NULL, 0, NULL, NULL);
if (cb == 0)
return (char *)git__calloc(1, sizeof(char));
ret = (char*)git__malloc(cb);
if (!ret)
return NULL;
if (WideCharToMultiByte(
_active_codepage, 0, str, -1, ret, (int)cb, NULL, NULL) == 0)
{
giterr_set(GITERR_OS, "Could not convert string to UTF-8");
git__free(ret);
ret = NULL;
}
return ret;
}