Open Chinese Convert 1.3.0.dirty
A project for conversion between Traditional and Simplified Chinese
Loading...
Searching...
No Matches
WinUtil.hpp
1/*
2 * Open Chinese Convert
3 *
4 * Copyright 2010-2026 Carbo Kuo and contributors
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19#pragma once
20
21#if defined(_WIN32) || defined(_WIN64)
22
23#ifndef NOMINMAX
24#define NOMINMAX
25#endif
26#include <Windows.h>
27
28#include <string>
29
30namespace opencc {
31namespace internal {
32
33inline std::string Utf8FromWide(const std::wstring& wide) {
34 if (wide.empty()) {
35 return "";
36 }
37 const int required =
38 WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, nullptr, 0, nullptr,
39 nullptr);
40 if (required <= 1) {
41 return "";
42 }
43 std::string utf8(static_cast<size_t>(required), '\0');
44 WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, utf8.data(), required,
45 nullptr, nullptr);
46 utf8.resize(static_cast<size_t>(required - 1));
47 return utf8;
48}
49
50inline std::wstring WideFromUtf8(const std::string& utf8) {
51 if (utf8.empty()) {
52 return L"";
53 }
54 const int required =
55 MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, nullptr, 0);
56 if (required <= 1) {
57 return L"";
58 }
59 std::wstring wide(static_cast<size_t>(required), L'\0');
60 MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, wide.data(), required);
61 wide.resize(static_cast<size_t>(required - 1));
62 return wide;
63}
64
65} // namespace internal
66} // namespace opencc
67
68#endif // defined(_WIN32) || defined(_WIN64)