1 // Copyright (c) 2012 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.
5 #include "base/i18n/icu_string_conversions.h"
13 #include "base/logging.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"
25 // ToUnicodeCallbackSubstitute() is based on UCNV_TO_U_CALLBACK_SUBSTITUTE
26 // in source/common/ucnv_err.c.
28 // Copyright (c) 1995-2006 International Business Machines Corporation
31 // All rights reserved.
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.
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.
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.
59 // ___________________________________________________________________________
61 // All trademarks and registered trademarks mentioned herein are the property
62 // of their respective owners.
64 void ToUnicodeCallbackSubstitute(const void* context,
65 UConverterToUnicodeArgs *to_args,
66 const char* code_units,
68 UConverterCallbackReason reason,
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)) {
76 ucnv_cbToUWriteUChars(to_args, &kReplacementChar, 1, 0, err);
78 // else the caller must have set the error code accordingly.
80 // else ignore the reset, close and clone calls.
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);
91 UErrorCode status = U_ZERO_ERROR;
93 // Setup our error handler.
95 case OnStringConversionError::FAIL:
96 ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_STOP, nullptr,
97 nullptr, nullptr, &status);
99 case OnStringConversionError::SKIP:
100 case OnStringConversionError::SUBSTITUTE:
101 ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_SKIP, nullptr,
102 nullptr, nullptr, &status);
108 // ucnv_fromUChars returns size not including terminating null
110 ucnv_fromUChars(converter, &(*encoded)[0], encoded_max_length, src.data(),
111 src.length(), &status);
112 encoded->resize(actual_size);
113 ucnv_close(converter);
114 if (U_SUCCESS(status))
116 encoded->clear(); // Make sure the output is empty on error.
120 // Set up our error handler for ToUTF-16 converters
121 void SetUpErrorHandlerForToUChars(OnStringConversionError::Type on_error,
122 UConverter* converter, UErrorCode* status) {
124 case OnStringConversionError::FAIL:
125 ucnv_setToUCallBack(converter, UCNV_TO_U_CALLBACK_STOP, nullptr, nullptr,
128 case OnStringConversionError::SKIP:
129 ucnv_setToUCallBack(converter, UCNV_TO_U_CALLBACK_SKIP, nullptr, nullptr,
132 case OnStringConversionError::SUBSTITUTE:
133 ucnv_setToUCallBack(converter, ToUnicodeCallbackSubstitute, nullptr,
134 nullptr, nullptr, status);
143 // Codepage <-> Wide/UTF-16 ---------------------------------------------------
145 bool UTF16ToCodepage(base::StringPiece16 utf16,
146 const char* codepage_name,
147 OnStringConversionError::Type on_error,
148 std::string* encoded) {
151 UErrorCode status = U_ZERO_ERROR;
152 UConverter* converter = ucnv_open(codepage_name, &status);
153 if (!U_SUCCESS(status))
156 return ConvertFromUTF16(converter, utf16, on_error, encoded);
159 bool CodepageToUTF16(base::StringPiece encoded,
160 const char* codepage_name,
161 OnStringConversionError::Type on_error,
165 UErrorCode status = U_ZERO_ERROR;
166 UConverter* converter = ucnv_open(codepage_name, &status);
167 if (!U_SUCCESS(status))
170 // Even in the worst case, the maximum length in 2-byte units of UTF-16
171 // output would be at most the same as the number of bytes in input. There
172 // is no single-byte encoding in which a character is mapped to a
173 // non-BMP character requiring two 2-byte units.
175 // Moreover, non-BMP characters in legacy multibyte encodings
176 // (e.g. EUC-JP, GB18030) take at least 2 bytes. The only exceptions are
177 // BOCU and SCSU, but we don't care about them.
178 size_t uchar_max_length = encoded.length() + 1;
180 SetUpErrorHandlerForToUChars(on_error, converter, &status);
181 std::unique_ptr<char16[]> buffer(new char16[uchar_max_length]);
182 int actual_size = ucnv_toUChars(converter, buffer.get(),
183 static_cast<int>(uchar_max_length), encoded.data(),
184 static_cast<int>(encoded.length()), &status);
185 ucnv_close(converter);
186 if (!U_SUCCESS(status)) {
187 utf16->clear(); // Make sure the output is empty on error.
191 utf16->assign(buffer.get(), actual_size);
195 bool ConvertToUtf8AndNormalize(base::StringPiece text,
196 const std::string& charset,
197 std::string* result) {
200 if (!CodepageToUTF16(text, charset.c_str(), OnStringConversionError::FAIL,
204 UErrorCode status = U_ZERO_ERROR;
205 const icu::Normalizer2* normalizer = icu::Normalizer2::getNFCInstance(status);
206 DCHECK(U_SUCCESS(status));
207 if (U_FAILURE(status))
209 int32_t utf16_length = static_cast<int32_t>(utf16.length());
210 icu::UnicodeString normalized(utf16.data(), utf16_length);
211 int32_t normalized_prefix_length =
212 normalizer->spanQuickCheckYes(normalized, status);
213 if (normalized_prefix_length < utf16_length) {
214 icu::UnicodeString un_normalized(normalized, normalized_prefix_length);
215 normalized.truncate(normalized_prefix_length);
216 normalizer->normalizeSecondAndAppend(normalized, un_normalized, status);
218 if (U_FAILURE(status))
220 normalized.toUTF8String(*result);