Win32.cxx 2.07 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * http://www.musicpd.org
 *
 * 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 2 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, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "Win32.hxx"
21
#include "system/Error.hxx"
22 23
#include "util/AllocatedString.hxx"

24 25
#include <memory>

26 27
#include <windows.h>

28
AllocatedString
29
WideCharToMultiByte(unsigned code_page, std::wstring_view src)
30
{
31 32
	int length = WideCharToMultiByte(code_page, 0, src.data(), src.size(),
					 nullptr, 0,
33 34
					 nullptr, nullptr);
	if (length <= 0)
35
		throw MakeLastError("Failed to convert from Unicode");
36

37
	auto buffer = std::make_unique<char[]>(length + 1);
38
	length = WideCharToMultiByte(code_page, 0, src.data(), src.size(),
39
				     buffer.get(), length,
40
				     nullptr, nullptr);
41
	if (length <= 0)
42
		throw MakeLastError("Failed to convert from Unicode");
43

44
	buffer[length] = '\0';
45
	return AllocatedString::Donate(buffer.release());
46 47
}

48
BasicAllocatedString<wchar_t>
49
MultiByteToWideChar(unsigned code_page, std::string_view src)
50
{
51 52
	int length = MultiByteToWideChar(code_page, 0, src.data(), src.size(),
					 nullptr, 0);
53
	if (length <= 0)
54
		throw MakeLastError("Failed to convert to Unicode");
55

56
	auto buffer = std::make_unique<wchar_t[]>(length + 1);
57
	length = MultiByteToWideChar(code_page, 0, src.data(), src.size(),
58
				     buffer.get(), length);
59
	if (length <= 0)
60
		throw MakeLastError("Failed to convert to Unicode");
61

62
	buffer[length] = L'\0';
63
	return BasicAllocatedString<wchar_t>::Donate(buffer.release());
64
}