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.
5 #include "base/i18n/icu_string_conversions.h"
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"
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);
106 // ucnv_fromUChars returns size not including terminating null
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))
114 encoded->clear(); // Make sure the output is empty on error.
118 // Set up our error handler for ToUTF-16 converters
119 void SetUpErrorHandlerForToUChars(OnStringConversionError::Type on_error,
120 UConverter* converter, UErrorCode* status) {
122 case OnStringConversionError::FAIL:
123 ucnv_setToUCallBack(converter, UCNV_TO_U_CALLBACK_STOP, nullptr, nullptr,
126 case OnStringConversionError::SKIP:
127 ucnv_setToUCallBack(converter, UCNV_TO_U_CALLBACK_SKIP, nullptr, nullptr,
130 case OnStringConversionError::SUBSTITUTE:
131 ucnv_setToUCallBack(converter, ToUnicodeCallbackSubstitute, nullptr,
132 nullptr, nullptr, status);
139 // Codepage <-> Wide/UTF-16 ---------------------------------------------------
141 bool UTF16ToCodepage(base::StringPiece16 utf16,
142 const char* codepage_name,
143 OnStringConversionError::Type on_error,
144 std::string* encoded) {
147 UErrorCode status = U_ZERO_ERROR;
148 UConverter* converter = ucnv_open(codepage_name, &status);
149 if (!U_SUCCESS(status))
152 return ConvertFromUTF16(converter, utf16, on_error, encoded);
155 bool CodepageToUTF16(base::StringPiece encoded,
156 const char* codepage_name,
157 OnStringConversionError::Type on_error,
158 std::u16string* utf16) {
161 UErrorCode status = U_ZERO_ERROR;
162 UConverter* converter = ucnv_open(codepage_name, &status);
163 if (!U_SUCCESS(status))
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.
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;
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.
187 utf16->assign(buffer.get(), actual_size);
191 bool ConvertToUtf8AndNormalize(base::StringPiece text,
192 const std::string& charset,
193 std::string* result) {
195 std::u16string utf16;
196 if (!CodepageToUTF16(text, charset.c_str(), OnStringConversionError::FAIL,
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))
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);
214 if (U_FAILURE(status))
216 normalized.toUTF8String(*result);