1 /*
2 * Copyright (C) 2020 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 "minikin/Buffer.h"
18
19 #include <gtest/gtest.h>
20
21 namespace minikin {
22
23 class TestObject {
24 public:
writeTo(BufferWriter * writer) const25 void writeTo(BufferWriter* writer) const {
26 // Total size = 20
27 // uint8_t (1)
28 writer->write<uint8_t>(0xAB);
29 // padding (1), uint16_t (2)
30 writer->write<uint16_t>(0xCDEF);
31 // uint8_t(1)
32 writer->write<uint8_t>(0x01);
33 // padding (3), array size (4), uint32_t (4) * 2
34 uint32_t uint32Array[] = {0x98765432, 0x98765433};
35 writer->writeArray<uint32_t>(uint32Array, 2);
36 }
37 };
38
TEST(BufferTest,testMeasureWriteRead)39 TEST(BufferTest, testMeasureWriteRead) {
40 TestObject testObject;
41 BufferWriter fakeWriter(nullptr);
42 testObject.writeTo(&fakeWriter);
43 ASSERT_EQ(fakeWriter.size(), 20u);
44 std::vector<uint8_t> buffer(fakeWriter.size());
45
46 BufferWriter writer(buffer.data());
47 testObject.writeTo(&writer);
48 ASSERT_EQ(writer.size(), buffer.size());
49
50 BufferReader reader(buffer.data());
51 ASSERT_EQ(reader.data(), buffer.data());
52 ASSERT_EQ(reader.pos(), 0u);
53 ASSERT_EQ(reader.read<uint8_t>(), 0xABu);
54 ASSERT_EQ(reader.pos(), 1u);
55 ASSERT_EQ(reader.read<uint16_t>(), 0xCDEFu);
56 ASSERT_EQ(reader.pos(), 4u);
57 ASSERT_EQ(reader.read<uint8_t>(), 0x01u);
58 ASSERT_EQ(reader.pos(), 5u);
59 auto [uint32Array, size] = reader.readArray<uint32_t>();
60 ASSERT_EQ(size, 2u);
61 ASSERT_EQ(uint32Array[0], 0x98765432u);
62 ASSERT_EQ(uint32Array[1], 0x98765433u);
63 ASSERT_EQ(reader.pos(), 20u);
64 }
65
TEST(BufferTest,testSkip)66 TEST(BufferTest, testSkip) {
67 TestObject testObject;
68 BufferWriter fakeWriter(nullptr);
69 testObject.writeTo(&fakeWriter);
70 ASSERT_EQ(fakeWriter.size(), 20u);
71 std::vector<uint8_t> buffer(fakeWriter.size());
72
73 BufferWriter writer(buffer.data());
74 testObject.writeTo(&writer);
75 ASSERT_EQ(writer.size(), buffer.size());
76
77 BufferReader reader(buffer.data());
78 ASSERT_EQ(reader.data(), buffer.data());
79 ASSERT_EQ(reader.pos(), 0u);
80 reader.skip<uint8_t>();
81 ASSERT_EQ(reader.pos(), 1u);
82 reader.read<uint16_t>();
83 ASSERT_EQ(reader.pos(), 4u);
84 reader.skip<uint8_t>();
85 ASSERT_EQ(reader.pos(), 5u);
86 reader.skipArray<uint32_t>();
87 ASSERT_EQ(reader.pos(), 20u);
88 }
89
90 } // namespace minikin
91