1 /*
2 * Copyright (C) 2018 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 "utils/strings/utf8.h"
18
19 #include "gmock/gmock.h"
20 #include "gtest/gtest.h"
21
22 namespace libtextclassifier3 {
23 namespace {
24
TEST(Utf8Test,ComputesUtf8LengthOfUnicodeCharacters)25 TEST(Utf8Test, ComputesUtf8LengthOfUnicodeCharacters) {
26 EXPECT_EQ(GetNumBytesForUTF8Char("\x00"), 1);
27 EXPECT_EQ(GetNumBytesForUTF8Char("h"), 1);
28 EXPECT_EQ(GetNumBytesForUTF8Char(""), 4);
29 EXPECT_EQ(GetNumBytesForUTF8Char("㍿"), 3);
30 }
31
TEST(Utf8Test,IsValidUTF8)32 TEST(Utf8Test, IsValidUTF8) {
33 EXPECT_TRUE(IsValidUTF8("1234hello", 13));
34 EXPECT_TRUE(IsValidUTF8("\u304A\u00B0\u106B", 8));
35 EXPECT_TRUE(IsValidUTF8("this is a test", 26));
36 EXPECT_TRUE(IsValidUTF8("\xf0\x9f\x98\x8b", 4));
37 // Example with first byte payload of zero.
38 EXPECT_TRUE(IsValidUTF8("\xf0\x90\x80\x80", 4));
39 // Too short (string is too short).
40 EXPECT_FALSE(IsValidUTF8("\xf0\x9f", 2));
41 // Too long (too many trailing bytes).
42 EXPECT_FALSE(IsValidUTF8("\xf0\x9f\x98\x8b\x8b", 5));
43 // Too short (too few trailing bytes).
44 EXPECT_FALSE(IsValidUTF8("\xf0\x9f\x98\x61\x61", 5));
45 // Invalid continuation byte (can be encoded in less bytes).
46 EXPECT_FALSE(IsValidUTF8("\xc0\x81", 2));
47 // Invalid continuation byte (can be encoded in less bytes).
48 EXPECT_FALSE(IsValidUTF8("\xf0\x8a\x85\x8f", 4));
49 }
50
TEST(Utf8Test,CorrectlyTruncatesStrings)51 TEST(Utf8Test, CorrectlyTruncatesStrings) {
52 EXPECT_EQ(SafeTruncateLength("FooBar", 3), 3);
53 EXPECT_EQ(SafeTruncateLength("früh", 3), 2);
54 EXPECT_EQ(SafeTruncateLength("مَمِمّمَّمِّ", 5), 4);
55 }
56
TEST(Utf8Test,CorrectlyConvertsFromUtf8)57 TEST(Utf8Test, CorrectlyConvertsFromUtf8) {
58 EXPECT_EQ(ValidCharToRune("a"), 97);
59 EXPECT_EQ(ValidCharToRune("\0"), 0);
60 EXPECT_EQ(ValidCharToRune("\u304A"), 0x304a);
61 EXPECT_EQ(ValidCharToRune("\xe3\x81\x8a"), 0x304a);
62 }
63
TEST(Utf8Test,CorrectlyConvertsToUtf8)64 TEST(Utf8Test, CorrectlyConvertsToUtf8) {
65 char utf8_encoding[4];
66 EXPECT_EQ(ValidRuneToChar(97, utf8_encoding), 1);
67 EXPECT_EQ(ValidRuneToChar(0, utf8_encoding), 1);
68 EXPECT_EQ(ValidRuneToChar(0x304a, utf8_encoding), 3);
69 }
70
71 } // namespace
72 } // namespace libtextclassifier3
73