Upload upstream chromium 85.0.4183.84
[platform/framework/web/chromium-efl.git] / base / i18n / icu_string_conversions.cc
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.
4
5 #include "base/i18n/icu_string_conversions.h"
6
7 #include <stddef.h>
8 #include <stdint.h>
9
10 #include <memory>
11 #include <vector>
12
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"
22
23 namespace base {
24
25 namespace {
26 // ToUnicodeCallbackSubstitute() is based on UCNV_TO_U_CALLBACK_SUBSTITUTE
27 // in source/common/ucnv_err.c.
28
29 // Copyright (c) 1995-2006 International Business Machines Corporation
30 // and others
31 //
32 // All rights reserved.
33 //
34
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.
44 //
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.
54 //
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.
59
60 //  ___________________________________________________________________________
61 //
62 // All trademarks and registered trademarks mentioned herein are the property
63 // of their respective owners.
64
65 void ToUnicodeCallbackSubstitute(const void* context,
66                                  UConverterToUnicodeArgs *to_args,
67                                  const char* code_units,
68                                  int32_t length,
69                                  UConverterCallbackReason reason,
70                                  UErrorCode * err) {
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)) {
76       *err = U_ZERO_ERROR;
77       ucnv_cbToUWriteUChars(to_args, &kReplacementChar, 1, 0, err);
78       }
79       // else the caller must have set the error code accordingly.
80   }
81   // else ignore the reset, close and clone calls.
82 }
83
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);
91
92   UErrorCode status = U_ZERO_ERROR;
93
94   // Setup our error handler.
95   switch (on_error) {
96     case OnStringConversionError::FAIL:
97       ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_STOP, nullptr,
98                             nullptr, nullptr, &status);
99       break;
100     case OnStringConversionError::SKIP:
101     case OnStringConversionError::SUBSTITUTE:
102       ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_SKIP, nullptr,
103                             nullptr, nullptr, &status);
104       break;
105     default:
106       NOTREACHED();
107   }
108
109   // ucnv_fromUChars returns size not including terminating null
110   int actual_size =
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))
116     return true;
117   encoded->clear();  // Make sure the output is empty on error.
118   return false;
119 }
120
121 // Set up our error handler for ToUTF-16 converters
122 void SetUpErrorHandlerForToUChars(OnStringConversionError::Type on_error,
123                                   UConverter* converter, UErrorCode* status) {
124   switch (on_error) {
125     case OnStringConversionError::FAIL:
126       ucnv_setToUCallBack(converter, UCNV_TO_U_CALLBACK_STOP, nullptr, nullptr,
127                           nullptr, status);
128       break;
129     case OnStringConversionError::SKIP:
130       ucnv_setToUCallBack(converter, UCNV_TO_U_CALLBACK_SKIP, nullptr, nullptr,
131                           nullptr, status);
132       break;
133     case OnStringConversionError::SUBSTITUTE:
134       ucnv_setToUCallBack(converter, ToUnicodeCallbackSubstitute, nullptr,
135                           nullptr, nullptr, status);
136       break;
137     default:
138       NOTREACHED();
139   }
140 }
141
142 }  // namespace
143
144 // Codepage <-> Wide/UTF-16  ---------------------------------------------------
145
146 bool UTF16ToCodepage(base::StringPiece16 utf16,
147                      const char* codepage_name,
148                      OnStringConversionError::Type on_error,
149                      std::string* encoded) {
150   encoded->clear();
151
152   UErrorCode status = U_ZERO_ERROR;
153   UConverter* converter = ucnv_open(codepage_name, &status);
154   if (!U_SUCCESS(status))
155     return false;
156
157   return ConvertFromUTF16(converter, utf16, on_error, encoded);
158 }
159
160 bool CodepageToUTF16(base::StringPiece encoded,
161                      const char* codepage_name,
162                      OnStringConversionError::Type on_error,
163                      string16* utf16) {
164   utf16->clear();
165
166   UErrorCode status = U_ZERO_ERROR;
167   UConverter* converter = ucnv_open(codepage_name, &status);
168   if (!U_SUCCESS(status))
169     return false;
170
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.
175   //
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;
180
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.
189     return false;
190   }
191
192   utf16->assign(buffer.get(), actual_size);
193   return true;
194 }
195
196 bool ConvertToUtf8AndNormalize(base::StringPiece text,
197                                const std::string& charset,
198                                std::string* result) {
199   result->clear();
200   string16 utf16;
201   if (!CodepageToUTF16(text, charset.c_str(), OnStringConversionError::FAIL,
202                        &utf16))
203     return false;
204
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))
209     return false;
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);
218   }
219   if (U_FAILURE(status))
220     return false;
221   normalized.toUTF8String(*result);
222   return true;
223 }
224
225 }  // namespace base