| 28 | } |
| 29 | |
| 30 | std::wstring StringUtilities::ToWString(const std::string& input) { |
| 31 | // Assumption: The wstring character count will be the same as the length of |
| 32 | // the string character count. Allocate the buffer with that many wchar_t items |
| 33 | // so that the first MultiByteToWideChar call will succeed most of the time as |
| 34 | // an optimization. |
| 35 | std::wstring output = L""; |
| 36 | int input_string_byte_count = static_cast<int>(input.size()) + 1; |
| 37 | int wide_string_length = input_string_byte_count; |
| 38 | std::vector<wchar_t> output_buffer(wide_string_length); |
| 39 | bool convert_failed = (0 == ::MultiByteToWideChar(CP_UTF8, |
| 40 | 0, |
| 41 | input.c_str(), |
| 42 | input_string_byte_count, |
| 43 | &output_buffer[0], |
| 44 | wide_string_length)); |
| 45 | if (convert_failed) { |
| 46 | if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER) { |
| 47 | // Buffer wasn't big enough. Call MultiByteToWideChar again with |
| 48 | // NULL values to determine how big the buffer should be. |
| 49 | wide_string_length = ::MultiByteToWideChar(CP_UTF8, |
| 50 | 0, |
| 51 | input.c_str(), |
| 52 | input_string_byte_count, |
| 53 | NULL, |
| 54 | 0); |
| 55 | output_buffer.resize(wide_string_length); |
| 56 | convert_failed = (0 == ::MultiByteToWideChar(CP_UTF8, |
| 57 | 0, |
| 58 | input.c_str(), |
| 59 | input_string_byte_count, |
| 60 | &output_buffer[0], |
| 61 | wide_string_length)); |
| 62 | if (!convert_failed) { |
| 63 | output = &output_buffer[0]; |
| 64 | } |
| 65 | } |
| 66 | } else { |
| 67 | output = &output_buffer[0]; |
| 68 | } |
| 69 | |
| 70 | return output; |
| 71 | } |
| 72 | |
| 73 | std::string StringUtilities::ToString(const std::wstring& input) { |
| 74 | // Assumption: The byte count of the resulting narrow string will be at most |