OpenVPN 3 Core Library
Loading...
Searching...
No Matches
wstring.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12#pragma once
13
14#ifdef _WIN32
15
16#include <string>
17#include <vector>
18#include <memory>
19
20namespace openvpn::wstring {
21
28inline std::wstring from_utf8(const std::string &str)
29{
30 std::wstring wStr; // enable RVO
31 if (str.empty())
32 return wStr;
33 const int str_size = static_cast<int>(str.size());
34 const auto reqSize = ::MultiByteToWideChar(CP_UTF8, 0, str.data(), str_size, nullptr, 0);
35 if (reqSize == 0)
36 throw std::runtime_error("MultiByteToWideChar(1) failed with code: [" + std::to_string(::GetLastError()) + "]");
37 wStr.resize(reqSize, L'\0'); // Allocate space
38 if (::MultiByteToWideChar(CP_UTF8, 0, str.data(), str_size, wStr.data(), reqSize) == 0)
39 throw std::runtime_error("MultiByteToWideChar(2) failed with code: [" + std::to_string(::GetLastError()) + "]");
40 return wStr;
41}
42
49inline std::string to_utf8(const std::wstring &wstr)
50{
51 std::string str; // For RVO
52 if (wstr.empty())
53 return str;
54 const int wstr_size = static_cast<int>(wstr.size());
55 const auto reqSize = ::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, nullptr, 0, nullptr, nullptr);
56 if (reqSize == 0)
57 throw std::runtime_error("WideCharToMultiByte(1) failed with code: [" + std::to_string(::GetLastError()) + "]");
58 str.resize(reqSize, '\0'); // Allocate space
59 if (::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, str.data(), reqSize, nullptr, nullptr) == 0)
60 throw std::runtime_error("WideCharToMultiByte(2) failed with code: [" + std::to_string(::GetLastError()) + "]");
61 return str;
62}
63
70inline std::unique_ptr<wchar_t[]> to_wchar_t(const std::wstring &wstr)
71{
72 const size_t len = wstr.length();
73 std::unique_ptr<wchar_t[]> ret(new wchar_t[len + 1]);
74 size_t i;
75 for (i = 0; i < len; ++i)
76 ret[i] = wstr[i];
77 ret[i] = L'\0';
78 return ret;
79}
80
92inline std::wstring pack_string_vector(const std::vector<std::string> &strvec)
93{
94 if (strvec.empty())
95 {
96 return std::wstring(2, L'\0'); // empty MULTI_SZ
97 }
98 std::wstring ret;
99 for (auto &s : strvec)
100 {
101 ret += from_utf8(s);
102 ret += L'\0';
103 }
104 ret += L'\0';
105 return ret;
106}
107
108#endif // #ifdef _WIN32
109}
std::string ret