Select Git revision
string_utils.cpp
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
string_utils.cpp 4.85 KiB
/*
* Copyright (C) 2004-2023 Savoir-faire Linux Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "string_utils.h"
#include <fmt/core.h>
#include <fmt/ranges.h>
#include <sstream>
#include <cctype>
#include <algorithm>
#include <ostream>
#include <iomanip>
#include <stdexcept>
#include <ios>
#include <charconv>
#include <string_view>
#ifdef _WIN32
#include <windows.h>
#include <oleauto.h>
#endif
#include <ciso646> // fix windows compiler bug
namespace dhtnet {
#ifdef _WIN32
std::wstring
to_wstring(const std::string& str, int codePage)
{
int srcLength = (int) str.length();
int requiredSize = MultiByteToWideChar(codePage, 0, str.c_str(), srcLength, nullptr, 0);
if (!requiredSize) {
throw std::runtime_error("Can't convert string to wstring");
}
std::wstring result((size_t) requiredSize, 0);
if (!MultiByteToWideChar(codePage, 0, str.c_str(), srcLength, &(*result.begin()), requiredSize)) {
throw std::runtime_error("Can't convert string to wstring");
}
return result;
}
std::string
to_string(const std::wstring& wstr, int codePage)
{
int srcLength = (int) wstr.length();
int requiredSize = WideCharToMultiByte(codePage, 0, wstr.c_str(), srcLength, nullptr, 0, 0, 0);
if (!requiredSize) {
throw std::runtime_error("Can't convert wstring to string");
}
std::string result((size_t) requiredSize, 0);
if (!WideCharToMultiByte(
codePage, 0, wstr.c_str(), srcLength, &(*result.begin()), requiredSize, 0, 0)) {
throw std::runtime_error("Can't convert wstring to string");
}
return result;
}