1 /*
2  * Copyright (C) 2022 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 "gtest/gtest.h"
18 
19 #include <array>
20 
21 #include "berberis/base/bit_util.h"
22 #include "string_offset_table.h"
23 
24 namespace nogrod {
25 
26 namespace {
27 
28 template <typename T>
RunSmokeTest()29 void RunSmokeTest() {
30   using berberis::bit_cast;
31   std::array<T, 10> data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
32 
33   if constexpr (sizeof(T) == 8) {
34     data[0] = uint32_t{0xFFFF'FFFFu};
35   }
36 
37   StringOffsetTable table(Buffer{bit_cast<const uint8_t*>(data.data()), data.size() * sizeof(T)});
38 
39   EXPECT_EQ(table.GetStringOffset(sizeof(T) * 2, 1), 3U);
40   EXPECT_EQ(table.GetStringOffset(sizeof(T) * 2, 5), 7U);
41   EXPECT_EQ(table.GetStringOffset(sizeof(T) * (data.size() - 1), 0), 9U);
42 
43   EXPECT_DEATH((void)table.GetStringOffset(sizeof(T) * 0, 2), "");
44   EXPECT_DEATH((void)table.GetStringOffset(sizeof(T) * (data.size()), 0), "");
45   EXPECT_DEATH((void)table.GetStringOffset(sizeof(T) * 2, data.size() - 2), "");
46 
47   // Unaligned access
48   EXPECT_DEATH((void)table.GetStringOffset(sizeof(T) * 2 + 1, 0), "");
49   EXPECT_DEATH((void)table.GetStringOffset(sizeof(T) * 2 + sizeof(T) / 2, 0), "");
50 }
51 
TEST(StringOffsetTalbe,Smoke32)52 TEST(StringOffsetTalbe, Smoke32) {
53   RunSmokeTest<uint32_t>();
54 }
55 
TEST(StringOffsetTalbe,Smoke64)56 TEST(StringOffsetTalbe, Smoke64) {
57   RunSmokeTest<uint64_t>();
58 }
59 
60 }  // namespace
61 
62 }  // namespace nogrod
63