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