admin
2023-03-07 8b06b1cbf112d55307ea8a6efe711db4e7506d89
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
 
#include "base/strings/utf_string_conversions.h"
 
#include <stdint.h>
 
#include <string>
 
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversion_utils.h"
#include "build/build_config.h"
 
namespace {
 
template<typename SRC_CHAR, typename DEST_STRING>
bool ConvertUnicode(const SRC_CHAR* src,
                    size_t src_len,
                    DEST_STRING* output) {
  bool success = true;
  int32_t src_len32 = static_cast<int32_t>(src_len);
  for (int32_t i = 0; i < src_len32; i++) {
    uint32_t code_point;
    if (base::ReadUnicodeCharacter(src, src_len32, &i, &code_point)) {
      base::WriteUnicodeCharacter(code_point, output);
    } else {
      base::WriteUnicodeCharacter(0xFFFD, output);
      success = false;
    }
  }
 
  return success;
}
 
}  // namespace
 
namespace base {
 
bool UTF8ToUTF16(const char* src, size_t src_len, string16* output) {
  base::PrepareForUTF16Or32Output(src, src_len, output);
  return ConvertUnicode(src, src_len, output);
}
 
string16 UTF8ToUTF16(const StringPiece& utf8) {
  string16 ret;
  UTF8ToUTF16(utf8.data(), utf8.length(), &ret);
  return ret;
}
 
bool UTF16ToUTF8(const char16* src, size_t src_len, std::string* output) {
  base::PrepareForUTF8Output(src, src_len, output);
  return ConvertUnicode(src, src_len, output);
}
 
std::string UTF16ToUTF8(const StringPiece16& utf16) {
  std::string ret;
  UTF16ToUTF8(utf16.data(), utf16.length(), &ret);
  return ret;
}
 
#if defined(WCHAR_T_IS_UTF16)
std::string WideToUTF8(WStringPiece wide) {
  std::string ret;
  UTF16ToUTF8(reinterpret_cast<const char16*>(wide.data()), wide.size(), &ret);
  return ret;
}
 
std::wstring UTF8ToWide(StringPiece utf8) {
  std::wstring ret;
  base::PrepareForUTF16Or32Output(utf8.data(), utf8.size(), &ret);
  ConvertUnicode(utf8.data(), utf8.size(), &ret);
  return ret;
}
#endif  // defined(WCHAR_T_IS_UTF16)
 
}  // namespace