• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "gmock/gmock.h"
18 #include "gtest/gtest.h"
19 
20 #include "utils/strings/utf8.h"
21 
22 namespace libtextclassifier3 {
23 namespace {
24 
TEST(Utf8Test,GetNumBytesForUTF8Char)25 TEST(Utf8Test, GetNumBytesForUTF8Char) {
26   EXPECT_EQ(GetNumBytesForUTF8Char("\x00"), 0);
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("1234��hello", 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   // Too short (string is too short).
38   EXPECT_FALSE(IsValidUTF8("\xf0\x9f", 2));
39   // Too long (too many trailing bytes).
40   EXPECT_FALSE(IsValidUTF8("\xf0\x9f\x98\x8b\x8b", 5));
41   // Too short (too few trailing bytes).
42   EXPECT_FALSE(IsValidUTF8("\xf0\x9f\x98\x61\x61", 5));
43 }
44 
TEST(Utf8Test,ValidUTF8CharLength)45 TEST(Utf8Test, ValidUTF8CharLength) {
46   EXPECT_EQ(ValidUTF8CharLength("1234��hello", 13), 1);
47   EXPECT_EQ(ValidUTF8CharLength("\u304A\u00B0\u106B", 8), 3);
48   EXPECT_EQ(ValidUTF8CharLength("this is a test������", 26), 1);
49   EXPECT_EQ(ValidUTF8CharLength("\xf0\x9f\x98\x8b", 4), 4);
50   // Too short (string is too short).
51   EXPECT_EQ(ValidUTF8CharLength("\xf0\x9f", 2), -1);
52   // Too long (too many trailing bytes). First character is valid.
53   EXPECT_EQ(ValidUTF8CharLength("\xf0\x9f\x98\x8b\x8b", 5), 4);
54   // Too short (too few trailing bytes).
55   EXPECT_EQ(ValidUTF8CharLength("\xf0\x9f\x98\x61\x61", 5), -1);
56 }
57 
58 }  // namespace
59 }  // namespace libtextclassifier3
60