summaryrefslogtreecommitdiff
path: root/src/third_party/wiredtiger/src/os_win/os_utf8.c
blob: 0f8fb66ff81c4ffe72c5f7d6c32ac2f0102a5171 (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
/*-
 * Copyright (c) 2014-present 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);
}