1 // Copyright 2006-2008 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/strings/sys_string_conversions.h"
6
7 #include <windows.h>
8
9 #include <stdint.h>
10
11 #include "base/strings/string_piece.h"
12
13 namespace base {
14
15 // Do not assert in this function since it is used by the asssertion code!
SysWideToUTF8(const std::wstring & wide)16 std::string SysWideToUTF8(const std::wstring& wide) {
17 return SysWideToMultiByte(wide, CP_UTF8);
18 }
19
20 // Do not assert in this function since it is used by the asssertion code!
SysUTF8ToWide(StringPiece utf8)21 std::wstring SysUTF8ToWide(StringPiece utf8) {
22 return SysMultiByteToWide(utf8, CP_UTF8);
23 }
24
SysWideToNativeMB(const std::wstring & wide)25 std::string SysWideToNativeMB(const std::wstring& wide) {
26 return SysWideToMultiByte(wide, CP_ACP);
27 }
28
SysNativeMBToWide(StringPiece native_mb)29 std::wstring SysNativeMBToWide(StringPiece native_mb) {
30 return SysMultiByteToWide(native_mb, CP_ACP);
31 }
32
33 // Do not assert in this function since it is used by the asssertion code!
SysMultiByteToWide(StringPiece mb,uint32_t code_page)34 std::wstring SysMultiByteToWide(StringPiece mb, uint32_t code_page) {
35 if (mb.empty())
36 return std::wstring();
37
38 int mb_length = static_cast<int>(mb.length());
39 // Compute the length of the buffer.
40 int charcount = MultiByteToWideChar(code_page, 0,
41 mb.data(), mb_length, NULL, 0);
42 if (charcount == 0)
43 return std::wstring();
44
45 std::wstring wide;
46 wide.resize(static_cast<size_t>(charcount));
47 MultiByteToWideChar(code_page, 0, mb.data(), mb_length, &wide[0], charcount);
48
49 return wide;
50 }
51
52 // Do not assert in this function since it is used by the asssertion code!
SysWideToMultiByte(const std::wstring & wide,uint32_t code_page)53 std::string SysWideToMultiByte(const std::wstring& wide, uint32_t code_page) {
54 int wide_length = static_cast<int>(wide.length());
55 if (wide_length == 0)
56 return std::string();
57
58 // Compute the length of the buffer we'll need.
59 int charcount = WideCharToMultiByte(code_page, 0, wide.data(), wide_length,
60 NULL, 0, NULL, NULL);
61 if (charcount == 0)
62 return std::string();
63
64 std::string mb;
65 mb.resize(static_cast<size_t>(charcount));
66 WideCharToMultiByte(code_page, 0, wide.data(), wide_length,
67 &mb[0], charcount, NULL, NULL);
68
69 return mb;
70 }
71
72 } // namespace base
73