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