1 /*
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 "util/BigBuffer.h"
18 
19 #include "test/Test.h"
20 
21 namespace aapt {
22 
TEST(BigBufferTest,AllocateSingleBlock)23 TEST(BigBufferTest, AllocateSingleBlock) {
24   BigBuffer buffer(4);
25 
26   EXPECT_NE(nullptr, buffer.NextBlock<char>(2));
27   EXPECT_EQ(2u, buffer.size());
28 }
29 
TEST(BigBufferTest,ReturnSameBlockIfNextAllocationFits)30 TEST(BigBufferTest, ReturnSameBlockIfNextAllocationFits) {
31   BigBuffer buffer(16);
32 
33   char* b1 = buffer.NextBlock<char>(8);
34   EXPECT_NE(nullptr, b1);
35 
36   char* b2 = buffer.NextBlock<char>(4);
37   EXPECT_NE(nullptr, b2);
38 
39   EXPECT_EQ(b1 + 8, b2);
40 }
41 
TEST(BigBufferTest,AllocateExactSizeBlockIfLargerThanBlockSize)42 TEST(BigBufferTest, AllocateExactSizeBlockIfLargerThanBlockSize) {
43   BigBuffer buffer(16);
44 
45   EXPECT_NE(nullptr, buffer.NextBlock<char>(32));
46   EXPECT_EQ(32u, buffer.size());
47 }
48 
TEST(BigBufferTest,AppendAndMoveBlock)49 TEST(BigBufferTest, AppendAndMoveBlock) {
50   BigBuffer buffer(16);
51 
52   uint32_t* b1 = buffer.NextBlock<uint32_t>();
53   ASSERT_NE(nullptr, b1);
54   *b1 = 33;
55 
56   {
57     BigBuffer buffer2(16);
58     b1 = buffer2.NextBlock<uint32_t>();
59     ASSERT_NE(nullptr, b1);
60     *b1 = 44;
61 
62     buffer.AppendBuffer(std::move(buffer2));
63     EXPECT_EQ(0u, buffer2.size());
64     EXPECT_EQ(buffer2.begin(), buffer2.end());
65   }
66 
67   EXPECT_EQ(2 * sizeof(uint32_t), buffer.size());
68 
69   auto b = buffer.begin();
70   ASSERT_NE(b, buffer.end());
71   ASSERT_EQ(sizeof(uint32_t), b->size);
72   ASSERT_EQ(33u, *reinterpret_cast<uint32_t*>(b->buffer.get()));
73   ++b;
74 
75   ASSERT_NE(b, buffer.end());
76   ASSERT_EQ(sizeof(uint32_t), b->size);
77   ASSERT_EQ(44u, *reinterpret_cast<uint32_t*>(b->buffer.get()));
78   ++b;
79 
80   ASSERT_EQ(b, buffer.end());
81 }
82 
TEST(BigBufferTest,PadAndAlignProperly)83 TEST(BigBufferTest, PadAndAlignProperly) {
84   BigBuffer buffer(16);
85 
86   ASSERT_NE(buffer.NextBlock<char>(2), nullptr);
87   ASSERT_EQ(2u, buffer.size());
88   buffer.Pad(2);
89   ASSERT_EQ(4u, buffer.size());
90   buffer.Align4();
91   ASSERT_EQ(4u, buffer.size());
92   buffer.Pad(2);
93   ASSERT_EQ(6u, buffer.size());
94   buffer.Align4();
95   ASSERT_EQ(8u, buffer.size());
96 }
97 
98 }  // namespace aapt
99