Celestia
1// winutil.cpp
2//
3// Copyright (C) 2019-present, Celestia Development Team
4// Copyright (C) 2002, Chris Laurel <claurel@shatters.net>
5//
6// Miscellaneous useful Windows-related functions.
7//
8// This program is free software; you can redistribute it and/or
9// modify it under the terms of the GNU General Public License
10// as published by the Free Software Foundation; either version 2
11// of the License, or (at your option) any later version.
12
13#include "winutil.h"
14
15#include <windows.h>
16
17namespace celestia::util
18{
19
20std::string
21WideToUTF8(std::wstring_view ws)
22{
23if (ws.empty())
24return {};
25
26// get a converted string length
27const auto srcLen = static_cast<int>(ws.size());
28int len = WideCharToMultiByte(CP_UTF8, 0, ws.data(), srcLen, nullptr, 0, nullptr, nullptr);
29if (len <= 0)
30return {};
31
32std::string out(static_cast<std::string::size_type>(len), '\0');
33len = WideCharToMultiByte(CP_UTF8, 0, ws.data(), srcLen, out.data(), len, nullptr, nullptr);
34if (len <= 0)
35return {};
36
37out.resize(static_cast<std::size_t>(len));
38return out;
39}
40
41} // end namespace celestia::util
42