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