blob: bbb54b1b1851df8a2e594eb39f9875cfd7d66579 [file] [log] [blame]
Elliott Hughesc1fd4922015-11-11 18:02:29 +00001/*
2* Copyright (C) 2015 The Android Open Source Project
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16
17#include "base/utf8.h"
18
19#include <gtest/gtest.h>
20
21#include "base/macros.h"
22
23namespace android {
24namespace base {
25
26TEST(UTFStringConversionsTest, ConvertInvalidUTF8) {
27 std::wstring wide;
28
29 // Standalone \xa2 is an invalid UTF-8 sequence, so this should return an
30 // error. Concatenate two C/C++ literal string constants to prevent the
31 // compiler from giving an error about "\xa2af" containing a "hex escape
32 // sequence out of range".
33 EXPECT_FALSE(android::base::UTF8ToWide("before\xa2" "after", &wide));
34
35 // Even if an invalid character is encountered, UTF8ToWide() should still do
36 // its best to convert the rest of the string. sysdeps_win32.cpp:
37 // _console_write_utf8() depends on this behavior.
38 //
39 // Thus, we verify that the valid characters are converted, but we ignore the
40 // specific replacement character that UTF8ToWide() may replace the invalid
41 // UTF-8 characters with because we want to allow that to change if the
42 // implementation changes.
43 EXPECT_EQ(0, wide.find(L"before"));
44 const wchar_t after_wide[] = L"after";
45 EXPECT_EQ(wide.length() - (arraysize(after_wide) - 1), wide.find(after_wide));
46}
47
48// Below is adapted from https://chromium.googlesource.com/chromium/src/+/master/base/strings/utf_string_conversions_unittest.cc
49
50// Copyright (c) 2010 The Chromium Authors. All rights reserved.
51// Use of this source code is governed by a BSD-style license that can be
52// found in the LICENSE file.
53
54// The tests below from utf_string_conversions_unittest.cc check for this
55// preprocessor symbol, so define it, as it is appropriate for Windows.
56#define WCHAR_T_IS_UTF16
57static_assert(sizeof(wchar_t) == 2, "wchar_t is not 2 bytes");
58
59// The tests below from utf_string_conversions_unittest.cc call versions of
60// UTF8ToWide() and WideToUTF8() that don't return success/failure, so these are
61// stub implementations with that signature. These are just for testing and
62// should not be moved to base because they assert/expect no errors which is
63// probably not a good idea (or at least it is something that should be left
64// up to the caller, not a base library).
65
66static std::wstring UTF8ToWide(const std::string& utf8) {
67 std::wstring utf16;
68 EXPECT_TRUE(UTF8ToWide(utf8, &utf16));
69 return utf16;
70}
71
72static std::string WideToUTF8(const std::wstring& utf16) {
73 std::string utf8;
74 EXPECT_TRUE(WideToUTF8(utf16, &utf8));
75 return utf8;
76}
77
78namespace {
79
80const wchar_t* const kConvertRoundtripCases[] = {
81 L"Google Video",
82 // "网页 图片 资讯更多 »"
83 L"\x7f51\x9875\x0020\x56fe\x7247\x0020\x8d44\x8baf\x66f4\x591a\x0020\x00bb",
84 // "Παγκόσμιος Ιστός"
85 L"\x03a0\x03b1\x03b3\x03ba\x03cc\x03c3\x03bc\x03b9"
86 L"\x03bf\x03c2\x0020\x0399\x03c3\x03c4\x03cc\x03c2",
87 // "Поиск страниц на русском"
88 L"\x041f\x043e\x0438\x0441\x043a\x0020\x0441\x0442"
89 L"\x0440\x0430\x043d\x0438\x0446\x0020\x043d\x0430"
90 L"\x0020\x0440\x0443\x0441\x0441\x043a\x043e\x043c",
91 // "전체서비스"
92 L"\xc804\xccb4\xc11c\xbe44\xc2a4",
93
94 // Test characters that take more than 16 bits. This will depend on whether
95 // wchar_t is 16 or 32 bits.
96#if defined(WCHAR_T_IS_UTF16)
97 L"\xd800\xdf00",
98 // ????? (Mathematical Alphanumeric Symbols (U+011d40 - U+011d44 : A,B,C,D,E)
99 L"\xd807\xdd40\xd807\xdd41\xd807\xdd42\xd807\xdd43\xd807\xdd44",
100#elif defined(WCHAR_T_IS_UTF32)
101 L"\x10300",
102 // ????? (Mathematical Alphanumeric Symbols (U+011d40 - U+011d44 : A,B,C,D,E)
103 L"\x11d40\x11d41\x11d42\x11d43\x11d44",
104#endif
105};
106
107} // namespace
108
109TEST(UTFStringConversionsTest, ConvertUTF8AndWide) {
110 // we round-trip all the wide strings through UTF-8 to make sure everything
111 // agrees on the conversion. This uses the stream operators to test them
112 // simultaneously.
113 for (size_t i = 0; i < arraysize(kConvertRoundtripCases); ++i) {
114 std::ostringstream utf8;
115 utf8 << WideToUTF8(kConvertRoundtripCases[i]);
116 std::wostringstream wide;
117 wide << UTF8ToWide(utf8.str());
118
119 EXPECT_EQ(kConvertRoundtripCases[i], wide.str());
120 }
121}
122
123TEST(UTFStringConversionsTest, ConvertUTF8AndWideEmptyString) {
124 // An empty std::wstring should be converted to an empty std::string,
125 // and vice versa.
126 std::wstring wempty;
127 std::string empty;
128 EXPECT_EQ(empty, WideToUTF8(wempty));
129 EXPECT_EQ(wempty, UTF8ToWide(empty));
130}
131
132TEST(UTFStringConversionsTest, ConvertUTF8ToWide) {
133 struct UTF8ToWideCase {
134 const char* utf8;
135 const wchar_t* wide;
136 bool success;
137 } convert_cases[] = {
138 // Regular UTF-8 input.
139 {"\xe4\xbd\xa0\xe5\xa5\xbd", L"\x4f60\x597d", true},
140 // Non-character is passed through.
141 {"\xef\xbf\xbfHello", L"\xffffHello", true},
142 // Truncated UTF-8 sequence.
143 {"\xe4\xa0\xe5\xa5\xbd", L"\xfffd\x597d", false},
144 // Truncated off the end.
145 {"\xe5\xa5\xbd\xe4\xa0", L"\x597d\xfffd", false},
146 // Non-shortest-form UTF-8.
147 {"\xf0\x84\xbd\xa0\xe5\xa5\xbd", L"\xfffd\x597d", false},
148 // This UTF-8 character decodes to a UTF-16 surrogate, which is illegal.
149 // Note that for whatever reason, this test fails on Windows XP.
150 {"\xed\xb0\x80", L"\xfffd", false},
151 // Non-BMP characters. The second is a non-character regarded as valid.
152 // The result will either be in UTF-16 or UTF-32.
153#if defined(WCHAR_T_IS_UTF16)
154 {"A\xF0\x90\x8C\x80z", L"A\xd800\xdf00z", true},
155 {"A\xF4\x8F\xBF\xBEz", L"A\xdbff\xdffez", true},
156#elif defined(WCHAR_T_IS_UTF32)
157 {"A\xF0\x90\x8C\x80z", L"A\x10300z", true},
158 {"A\xF4\x8F\xBF\xBEz", L"A\x10fffez", true},
159#endif
160 };
161
162 for (size_t i = 0; i < arraysize(convert_cases); i++) {
163 std::wstring converted;
164 const bool success = UTF8ToWide(convert_cases[i].utf8,
165 strlen(convert_cases[i].utf8),
166 &converted);
167 EXPECT_EQ(convert_cases[i].success, success);
168 // The original test always compared expected and converted, but don't do
169 // that because our implementation of UTF8ToWide() does not guarantee to
170 // produce the same output in error situations.
171 if (success) {
172 std::wstring expected(convert_cases[i].wide);
173 EXPECT_EQ(expected, converted);
174 }
175 }
176
177 // Manually test an embedded NULL.
178 std::wstring converted;
179 EXPECT_TRUE(UTF8ToWide("\00Z\t", 3, &converted));
180 ASSERT_EQ(3U, converted.length());
181 EXPECT_EQ(static_cast<wchar_t>(0), converted[0]);
182 EXPECT_EQ('Z', converted[1]);
183 EXPECT_EQ('\t', converted[2]);
184
185 // Make sure that conversion replaces, not appends.
186 EXPECT_TRUE(UTF8ToWide("B", 1, &converted));
187 ASSERT_EQ(1U, converted.length());
188 EXPECT_EQ('B', converted[0]);
189}
190
191#if defined(WCHAR_T_IS_UTF16)
192// This test is only valid when wchar_t == UTF-16.
193TEST(UTFStringConversionsTest, ConvertUTF16ToUTF8) {
194 struct WideToUTF8Case {
195 const wchar_t* utf16;
196 const char* utf8;
197 bool success;
198 } convert_cases[] = {
199 // Regular UTF-16 input.
200 {L"\x4f60\x597d", "\xe4\xbd\xa0\xe5\xa5\xbd", true},
201 // Test a non-BMP character.
202 {L"\xd800\xdf00", "\xF0\x90\x8C\x80", true},
203 // Non-characters are passed through.
204 {L"\xffffHello", "\xEF\xBF\xBFHello", true},
205 {L"\xdbff\xdffeHello", "\xF4\x8F\xBF\xBEHello", true},
206 // The first character is a truncated UTF-16 character.
207 // Note that for whatever reason, this test fails on Windows XP.
208 {L"\xd800\x597d", "\xef\xbf\xbd\xe5\xa5\xbd",
209#if (WINVER >= 0x0600)
210 // Only Vista and later has a new API/flag that correctly returns false.
211 false
212#else
213 true
214#endif
215 },
216 // Truncated at the end.
217 // Note that for whatever reason, this test fails on Windows XP.
218 {L"\x597d\xd800", "\xe5\xa5\xbd\xef\xbf\xbd",
219#if (WINVER >= 0x0600)
220 // Only Vista and later has a new API/flag that correctly returns false.
221 false
222#else
223 true
224#endif
225 },
226 };
227
228 for (size_t i = 0; i < arraysize(convert_cases); i++) {
229 std::string converted;
230 const bool success = WideToUTF8(convert_cases[i].utf16,
231 wcslen(convert_cases[i].utf16),
232 &converted);
233 EXPECT_EQ(convert_cases[i].success, success);
234 // The original test always compared expected and converted, but don't do
235 // that because our implementation of WideToUTF8() does not guarantee to
236 // produce the same output in error situations.
237 if (success) {
238 std::string expected(convert_cases[i].utf8);
239 EXPECT_EQ(expected, converted);
240 }
241 }
242}
243
244#elif defined(WCHAR_T_IS_UTF32)
245// This test is only valid when wchar_t == UTF-32.
246TEST(UTFStringConversionsTest, ConvertUTF32ToUTF8) {
247 struct WideToUTF8Case {
248 const wchar_t* utf32;
249 const char* utf8;
250 bool success;
251 } convert_cases[] = {
252 // Regular 16-bit input.
253 {L"\x4f60\x597d", "\xe4\xbd\xa0\xe5\xa5\xbd", true},
254 // Test a non-BMP character.
255 {L"A\x10300z", "A\xF0\x90\x8C\x80z", true},
256 // Non-characters are passed through.
257 {L"\xffffHello", "\xEF\xBF\xBFHello", true},
258 {L"\x10fffeHello", "\xF4\x8F\xBF\xBEHello", true},
259 // Invalid Unicode code points.
260 {L"\xfffffffHello", "\xEF\xBF\xBDHello", false},
261 // The first character is a truncated UTF-16 character.
262 {L"\xd800\x597d", "\xef\xbf\xbd\xe5\xa5\xbd", false},
263 {L"\xdc01Hello", "\xef\xbf\xbdHello", false},
264 };
265
266 for (size_t i = 0; i < arraysize(convert_cases); i++) {
267 std::string converted;
268 EXPECT_EQ(convert_cases[i].success,
269 WideToUTF8(convert_cases[i].utf32,
270 wcslen(convert_cases[i].utf32),
271 &converted));
272 std::string expected(convert_cases[i].utf8);
273 EXPECT_EQ(expected, converted);
274 }
275}
276#endif // defined(WCHAR_T_IS_UTF32)
277
278// The test below uses these types and functions, so just do enough to get the
279// test running.
280typedef wchar_t char16;
281typedef std::wstring string16;
282
283template<typename T>
284static void* WriteInto(T* t, size_t size) {
285 // std::(w)string::resize() already includes space for a NULL terminator.
286 t->resize(size - 1);
287 return &(*t)[0];
288}
289
290// A stub implementation that calls a helper from above, just to get the test
291// below working. This is just for testing and should not be moved to base
292// because this ignores errors which is probably not a good idea, plus it takes
293// a string16 type which we don't really have.
294static std::string UTF16ToUTF8(const string16& utf16) {
295 return WideToUTF8(utf16);
296}
297
298TEST(UTFStringConversionsTest, ConvertMultiString) {
299 static char16 multi16[] = {
300 'f', 'o', 'o', '\0',
301 'b', 'a', 'r', '\0',
302 'b', 'a', 'z', '\0',
303 '\0'
304 };
305 static char multi[] = {
306 'f', 'o', 'o', '\0',
307 'b', 'a', 'r', '\0',
308 'b', 'a', 'z', '\0',
309 '\0'
310 };
311 string16 multistring16;
312 memcpy(WriteInto(&multistring16, arraysize(multi16)), multi16,
313 sizeof(multi16));
314 EXPECT_EQ(arraysize(multi16) - 1, multistring16.length());
315 std::string expected;
316 memcpy(WriteInto(&expected, arraysize(multi)), multi, sizeof(multi));
317 EXPECT_EQ(arraysize(multi) - 1, expected.length());
318 const std::string& converted = UTF16ToUTF8(multistring16);
319 EXPECT_EQ(arraysize(multi) - 1, converted.length());
320 EXPECT_EQ(expected, converted);
321}
322
323// The tests below from sys_string_conversions_unittest.cc call SysWideToUTF8()
324// and SysUTF8ToWide(), so these are stub implementations that call the helpers
325// above. These are just for testing and should not be moved to base because
326// they ignore errors which is probably not a good idea.
327
328static std::string SysWideToUTF8(const std::wstring& utf16) {
329 return WideToUTF8(utf16);
330}
331
332static std::wstring SysUTF8ToWide(const std::string& utf8) {
333 return UTF8ToWide(utf8);
334}
335
336// Below is adapted from https://chromium.googlesource.com/chromium/src/+/master/base/strings/sys_string_conversions_unittest.cc
337
338// Copyright (c) 2011 The Chromium Authors. All rights reserved.
339// Use of this source code is governed by a BSD-style license that can be
340// found in the LICENSE file.
341
342#ifdef WCHAR_T_IS_UTF32
343static const std::wstring kSysWideOldItalicLetterA = L"\x10300";
344#else
345static const std::wstring kSysWideOldItalicLetterA = L"\xd800\xdf00";
346#endif
347
348TEST(SysStrings, SysWideToUTF8) {
349 EXPECT_EQ("Hello, world", SysWideToUTF8(L"Hello, world"));
350 EXPECT_EQ("\xe4\xbd\xa0\xe5\xa5\xbd", SysWideToUTF8(L"\x4f60\x597d"));
351
352 // >16 bits
353 EXPECT_EQ("\xF0\x90\x8C\x80", SysWideToUTF8(kSysWideOldItalicLetterA));
354
355 // Error case. When Windows finds a UTF-16 character going off the end of
356 // a string, it just converts that literal value to UTF-8, even though this
357 // is invalid.
358 //
359 // This is what XP does, but Vista has different behavior, so we don't bother
360 // verifying it:
361 // EXPECT_EQ("\xE4\xBD\xA0\xED\xA0\x80zyxw",
362 // SysWideToUTF8(L"\x4f60\xd800zyxw"));
363
364 // Test embedded NULLs.
365 std::wstring wide_null(L"a");
366 wide_null.push_back(0);
367 wide_null.push_back('b');
368
369 std::string expected_null("a");
370 expected_null.push_back(0);
371 expected_null.push_back('b');
372
373 EXPECT_EQ(expected_null, SysWideToUTF8(wide_null));
374}
375
376TEST(SysStrings, SysUTF8ToWide) {
377 EXPECT_EQ(L"Hello, world", SysUTF8ToWide("Hello, world"));
378 EXPECT_EQ(L"\x4f60\x597d", SysUTF8ToWide("\xe4\xbd\xa0\xe5\xa5\xbd"));
379 // >16 bits
380 EXPECT_EQ(kSysWideOldItalicLetterA, SysUTF8ToWide("\xF0\x90\x8C\x80"));
381
382 // Error case. When Windows finds an invalid UTF-8 character, it just skips
383 // it. This seems weird because it's inconsistent with the reverse conversion.
384 //
385 // This is what XP does, but Vista has different behavior, so we don't bother
386 // verifying it:
387 // EXPECT_EQ(L"\x4f60zyxw", SysUTF8ToWide("\xe4\xbd\xa0\xe5\xa5zyxw"));
388
389 // Test embedded NULLs.
390 std::string utf8_null("a");
391 utf8_null.push_back(0);
392 utf8_null.push_back('b');
393
394 std::wstring expected_null(L"a");
395 expected_null.push_back(0);
396 expected_null.push_back('b');
397
398 EXPECT_EQ(expected_null, SysUTF8ToWide(utf8_null));
399}
400
401} // namespace base
402} // namespace android