summaryrefslogtreecommitdiff
path: root/src/third_party/wiredtiger/src/os_win/os_utf8.c
blob: 1c9efe3950688afe07b45d02da8ed2b5d2374fb3 (plain)
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
/*-
 * Copyright (c) 2014-2018 MongoDB, Inc.
 * Copyright (c) 2008-2014 WiredTiger, Inc.
 *	All rights reserved.
 *
 * See the file LICENSE for redistribution information.
 */

#include "wt_internal.h"

/*
 * __wt_to_utf16_string --
 *  Convert UTF-8 encoded string to UTF-16.
 */
int
__wt_to_utf16_string(
    WT_SESSION_IMPL *session, const char *utf8, WT_ITEM **outbuf)
{
	DWORD windows_error;
	int bufferSize;

	bufferSize = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
	windows_error = __wt_getlasterror();

	if (bufferSize == 0 && windows_error != ERROR_INSUFFICIENT_BUFFER) {
		__wt_errx(session, "MultiByteToWideChar: %s",
		    __wt_formatmessage(session, windows_error));
		return (__wt_map_windows_error(windows_error));
	}

	WT_RET(__wt_scr_alloc(session, bufferSize * sizeof(wchar_t), outbuf));
	bufferSize = MultiByteToWideChar(
	    CP_UTF8, 0, utf8, -1, (*outbuf)->mem, bufferSize);

	if (bufferSize == 0) {
		windows_error = __wt_getlasterror();
		__wt_scr_free(session, outbuf);
		__wt_errx(session, "MultiByteToWideChar: %s",
		    __wt_formatmessage(session, windows_error));
		return (__wt_map_windows_error(windows_error));
	}

	(*outbuf)->size = bufferSize;
	return (0);
}

/*
 * __wt_to_utf8_string --
 *  Convert UTF-16 encoded string to UTF-8.
 */
int
__wt_to_utf8_string(
    WT_SESSION_IMPL *session, const wchar_t *wide, WT_ITEM **outbuf)
{
	DWORD windows_error;
	int bufferSize;

	bufferSize = WideCharToMultiByte(
	    CP_UTF8, 0, wide, -1, NULL, 0, NULL, NULL);
	windows_error = __wt_getlasterror();

	if (bufferSize == 0 && windows_error != ERROR_INSUFFICIENT_BUFFER) {
		__wt_errx(session, "WideCharToMultiByte: %s",
		    __wt_formatmessage(session, windows_error));
		return (__wt_map_windows_error(windows_error));
	}

	WT_RET(__wt_scr_alloc(session, bufferSize, outbuf));

	bufferSize = WideCharToMultiByte(
	    CP_UTF8, 0, wide, -1, (*outbuf)->mem, bufferSize, NULL, NULL);
	if (bufferSize == 0) {
		windows_error = __wt_getlasterror();
		__wt_scr_free(session, outbuf);
		__wt_errx(session, "WideCharToMultiByte: %s",
		    __wt_formatmessage(session, windows_error));
		return (__wt_map_windows_error(windows_error));
	}

	(*outbuf)->size = bufferSize;
	return (0);
}