utf-conv.c 1.78 KB
Newer Older
1
/*
schu committed
2
 * Copyright (C) 2009-2012 the libgit2 contributors
3 4 5 6 7 8
 *
 * 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"
9
#include "utf-conv.h"
10
#include "git2/windows.h"
11

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/*
 * 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)
33 34
{
	wchar_t* ret;
35
	int cb;
36

37
	if (!str)
38 39
		return NULL;

40
	cb = MultiByteToWideChar(_active_codepage, 0, str, -1, NULL, 0);
41 42
	if (cb == 0)
		return (wchar_t *)git__calloc(1, sizeof(wchar_t));
43

44
	ret = (wchar_t *)git__malloc(cb * sizeof(wchar_t));
45 46
	if (!ret)
		return NULL;
47

48
	if (MultiByteToWideChar(_active_codepage, 0, str, -1, ret, (int)cb) == 0) {
49
		giterr_set(GITERR_OS, "Could not convert string to UTF-16");
50
		git__free(ret);
51 52 53 54 55 56
		ret = NULL;
	}

	return ret;
}

57 58
int gitwin_append_utf16(wchar_t *buffer, const char *str, size_t len)
{
59 60
	int result = MultiByteToWideChar(
		_active_codepage, 0, str, -1, buffer, (int)len);
61 62 63
	if (result == 0)
		giterr_set(GITERR_OS, "Could not convert string to UTF-16");
	return result;
64 65
}

66
char* gitwin_from_utf16(const wchar_t* str)
67 68
{
	char* ret;
69
	int cb;
70

71
	if (!str)
72 73
		return NULL;

74
	cb = WideCharToMultiByte(_active_codepage, 0, str, -1, NULL, 0, NULL, NULL);
75 76
	if (cb == 0)
		return (char *)git__calloc(1, sizeof(char));
77 78

	ret = (char*)git__malloc(cb);
79 80
	if (!ret)
		return NULL;
81

82 83 84
	if (WideCharToMultiByte(
		_active_codepage, 0, str, -1, ret, (int)cb, NULL, NULL) == 0)
	{
85
		giterr_set(GITERR_OS, "Could not convert string to UTF-8");
86
		git__free(ret);
87 88 89 90 91 92
		ret = NULL;
	}

	return ret;

}