| 1 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
| 2 |
/* vim: set ts=8 sts=2 et sw=2 tw=80: */ |
| 3 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
#include "WindowsUnicode.h" |
| 8 |
|
| 9 |
#include <windows.h> |
| 10 |
// For UNICODE_STRING |
| 11 |
#include <winternl.h> |
| 12 |
|
| 13 |
#include <string.h> |
| 14 |
|
| 15 |
namespace mozilla { |
| 16 |
namespace glue { |
| 17 |
|
| 18 |
mozilla::UniquePtr<char[]> WideToUTF8(const wchar_t* aStr, |
| 19 |
const size_t aStrLenExclNul) { |
| 20 |
int numConv = ::WideCharToMultiByte(CP_UTF8, 0, aStr, aStrLenExclNul, nullptr, |
| 21 |
0, nullptr, nullptr); |
| 22 |
if (!numConv) { |
| 23 |
return nullptr; |
| 24 |
} |
| 25 |
|
| 26 |
// Include room for the null terminator by adding one |
| 27 |
auto buf = mozilla::MakeUnique<char[]>(numConv + 1); |
| 28 |
|
| 29 |
numConv = ::WideCharToMultiByte(CP_UTF8, 0, aStr, aStrLenExclNul, buf.get(), |
| 30 |
numConv, nullptr, nullptr); |
| 31 |
if (!numConv) { |
| 32 |
return nullptr; |
| 33 |
} |
| 34 |
|
| 35 |
// Add null termination. numConv does not include the terminator, so we don't |
| 36 |
// subtract 1 when indexing into buf. |
| 37 |
buf[numConv] = 0; |
| 38 |
|
| 39 |
return buf; |
| 40 |
} |
| 41 |
|
| 42 |
mozilla::UniquePtr<char[]> WideToUTF8(const wchar_t* aStr) { |
| 43 |
return WideToUTF8(aStr, wcslen(aStr)); |
| 44 |
} |
| 45 |
|
| 46 |
mozilla::UniquePtr<char[]> WideToUTF8(const std::wstring& aStr) { |
| 47 |
return WideToUTF8(aStr.data(), aStr.length()); |
| 48 |
} |
| 49 |
|
| 50 |
mozilla::UniquePtr<char[]> WideToUTF8(PCUNICODE_STRING aStr) { |
| 51 |
if (!aStr) { |
| 52 |
return nullptr; |
| 53 |
} |
| 54 |
|
| 55 |
return WideToUTF8(aStr->Buffer, aStr->Length / sizeof(WCHAR)); |
| 56 |
} |
| 57 |
|
| 58 |
} // namespace glue |
| 59 |
} // namespace mozilla |