1 // Copyright 2012 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/i18n/icu_string_conversions.h"
6
7 #include <stddef.h>
8 #include <stdint.h>
9
10 #include <memory>
11
12 #include "base/check.h"
13 #include "base/notreached.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "third_party/icu/source/common/unicode/normalizer2.h"
17 #include "third_party/icu/source/common/unicode/ucnv.h"
18 #include "third_party/icu/source/common/unicode/ucnv_cb.h"
19 #include "third_party/icu/source/common/unicode/ucnv_err.h"
20 #include "third_party/icu/source/common/unicode/ustring.h"
21
22 namespace base {
23
24 namespace {
25 // ToUnicodeCallbackSubstitute() is based on UCNV_TO_U_CALLBACK_SUBSTITUTE
26 // in source/common/ucnv_err.c.
27
28 // Copyright (c) 1995-2006 International Business Machines Corporation
29 // and others
30 //
31 // All rights reserved.
32 //
33
34 // Permission is hereby granted, free of charge, to any person obtaining a
35 // copy of this software and associated documentation files (the "Software"),
36 // to deal in the Software without restriction, including without limitation
37 // the rights to use, copy, modify, merge, publish, distribute, and/or
38 // sell copies of the Software, and to permit persons to whom the Software
39 // is furnished to do so, provided that the above copyright notice(s) and
40 // this permission notice appear in all copies of the Software and that
41 // both the above copyright notice(s) and this permission notice appear in
42 // supporting documentation.
43 //
44 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
45 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
46 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
47 // OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
48 // INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
49 // OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
50 // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
51 // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
52 // OR PERFORMANCE OF THIS SOFTWARE.
53 //
54 // Except as contained in this notice, the name of a copyright holder
55 // shall not be used in advertising or otherwise to promote the sale, use
56 // or other dealings in this Software without prior written authorization
57 // of the copyright holder.
58
59 // ___________________________________________________________________________
60 //
61 // All trademarks and registered trademarks mentioned herein are the property
62 // of their respective owners.
63
ToUnicodeCallbackSubstitute(const void * context,UConverterToUnicodeArgs * to_args,const char * code_units,int32_t length,UConverterCallbackReason reason,UErrorCode * err)64 void ToUnicodeCallbackSubstitute(const void* context,
65 UConverterToUnicodeArgs *to_args,
66 const char* code_units,
67 int32_t length,
68 UConverterCallbackReason reason,
69 UErrorCode * err) {
70 static const UChar kReplacementChar = 0xFFFD;
71 if (reason <= UCNV_IRREGULAR) {
72 if (context == nullptr ||
73 (*(reinterpret_cast<const char*>(context)) == 'i' &&
74 reason == UCNV_UNASSIGNED)) {
75 *err = U_ZERO_ERROR;
76 ucnv_cbToUWriteUChars(to_args, &kReplacementChar, 1, 0, err);
77 }
78 // else the caller must have set the error code accordingly.
79 }
80 // else ignore the reset, close and clone calls.
81 }
82
ConvertFromUTF16(UConverter * converter,base::StringPiece16 src,OnStringConversionError::Type on_error,std::string * encoded)83 bool ConvertFromUTF16(UConverter* converter,
84 base::StringPiece16 src,
85 OnStringConversionError::Type on_error,
86 std::string* encoded) {
87 int encoded_max_length = UCNV_GET_MAX_BYTES_FOR_STRING(
88 src.length(), ucnv_getMaxCharSize(converter));
89 encoded->resize(encoded_max_length);
90
91 UErrorCode status = U_ZERO_ERROR;
92
93 // Setup our error handler.
94 switch (on_error) {
95 case OnStringConversionError::FAIL:
96 ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_STOP, nullptr,
97 nullptr, nullptr, &status);
98 break;
99 case OnStringConversionError::SKIP:
100 case OnStringConversionError::SUBSTITUTE:
101 ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_SKIP, nullptr,
102 nullptr, nullptr, &status);
103 break;
104 }
105
106 // ucnv_fromUChars returns size not including terminating null
107 int actual_size =
108 ucnv_fromUChars(converter, &(*encoded)[0], encoded_max_length, src.data(),
109 src.length(), &status);
110 encoded->resize(actual_size);
111 ucnv_close(converter);
112 if (U_SUCCESS(status))
113 return true;
114 encoded->clear(); // Make sure the output is empty on error.
115 return false;
116 }
117
118 // Set up our error handler for ToUTF-16 converters
SetUpErrorHandlerForToUChars(OnStringConversionError::Type on_error,UConverter * converter,UErrorCode * status)119 void SetUpErrorHandlerForToUChars(OnStringConversionError::Type on_error,
120 UConverter* converter, UErrorCode* status) {
121 switch (on_error) {
122 case OnStringConversionError::FAIL:
123 ucnv_setToUCallBack(converter, UCNV_TO_U_CALLBACK_STOP, nullptr, nullptr,
124 nullptr, status);
125 break;
126 case OnStringConversionError::SKIP:
127 ucnv_setToUCallBack(converter, UCNV_TO_U_CALLBACK_SKIP, nullptr, nullptr,
128 nullptr, status);
129 break;
130 case OnStringConversionError::SUBSTITUTE:
131 ucnv_setToUCallBack(converter, ToUnicodeCallbackSubstitute, nullptr,
132 nullptr, nullptr, status);
133 break;
134 }
135 }
136
137 } // namespace
138
139 // Codepage <-> Wide/UTF-16 ---------------------------------------------------
140
UTF16ToCodepage(base::StringPiece16 utf16,const char * codepage_name,OnStringConversionError::Type on_error,std::string * encoded)141 bool UTF16ToCodepage(base::StringPiece16 utf16,
142 const char* codepage_name,
143 OnStringConversionError::Type on_error,
144 std::string* encoded) {
145 encoded->clear();
146
147 UErrorCode status = U_ZERO_ERROR;
148 UConverter* converter = ucnv_open(codepage_name, &status);
149 if (!U_SUCCESS(status))
150 return false;
151
152 return ConvertFromUTF16(converter, utf16, on_error, encoded);
153 }
154
CodepageToUTF16(base::StringPiece encoded,const char * codepage_name,OnStringConversionError::Type on_error,std::u16string * utf16)155 bool CodepageToUTF16(base::StringPiece encoded,
156 const char* codepage_name,
157 OnStringConversionError::Type on_error,
158 std::u16string* utf16) {
159 utf16->clear();
160
161 UErrorCode status = U_ZERO_ERROR;
162 UConverter* converter = ucnv_open(codepage_name, &status);
163 if (!U_SUCCESS(status))
164 return false;
165
166 // Even in the worst case, the maximum length in 2-byte units of UTF-16
167 // output would be at most the same as the number of bytes in input. There
168 // is no single-byte encoding in which a character is mapped to a
169 // non-BMP character requiring two 2-byte units.
170 //
171 // Moreover, non-BMP characters in legacy multibyte encodings
172 // (e.g. EUC-JP, GB18030) take at least 2 bytes. The only exceptions are
173 // BOCU and SCSU, but we don't care about them.
174 size_t uchar_max_length = encoded.length() + 1;
175
176 SetUpErrorHandlerForToUChars(on_error, converter, &status);
177 std::unique_ptr<char16_t[]> buffer(new char16_t[uchar_max_length]);
178 int actual_size = ucnv_toUChars(
179 converter, buffer.get(), static_cast<int>(uchar_max_length),
180 encoded.data(), static_cast<int>(encoded.length()), &status);
181 ucnv_close(converter);
182 if (!U_SUCCESS(status)) {
183 utf16->clear(); // Make sure the output is empty on error.
184 return false;
185 }
186
187 utf16->assign(buffer.get(), actual_size);
188 return true;
189 }
190
ConvertToUtf8AndNormalize(base::StringPiece text,const std::string & charset,std::string * result)191 bool ConvertToUtf8AndNormalize(base::StringPiece text,
192 const std::string& charset,
193 std::string* result) {
194 result->clear();
195 std::u16string utf16;
196 if (!CodepageToUTF16(text, charset.c_str(), OnStringConversionError::FAIL,
197 &utf16))
198 return false;
199
200 UErrorCode status = U_ZERO_ERROR;
201 const icu::Normalizer2* normalizer = icu::Normalizer2::getNFCInstance(status);
202 DCHECK(U_SUCCESS(status));
203 if (U_FAILURE(status))
204 return false;
205 int32_t utf16_length = static_cast<int32_t>(utf16.length());
206 icu::UnicodeString normalized(utf16.data(), utf16_length);
207 int32_t normalized_prefix_length =
208 normalizer->spanQuickCheckYes(normalized, status);
209 if (normalized_prefix_length < utf16_length) {
210 icu::UnicodeString un_normalized(normalized, normalized_prefix_length);
211 normalized.truncate(normalized_prefix_length);
212 normalizer->normalizeSecondAndAppend(normalized, un_normalized, status);
213 }
214 if (U_FAILURE(status))
215 return false;
216 normalized.toUTF8String(*result);
217 return true;
218 }
219
220 } // namespace base
221