1 // Tencent is pleased to support the open source community by making RapidJSON available.
2 //
3 // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
4 //
5 // Licensed under the MIT License (the "License"); you may not use this file except
6 // in compliance with the License. You may obtain a copy of the License at
7 //
8 // http://opensource.org/licenses/MIT
9 //
10 // Unless required by applicable law or agreed to in writing, software distributed
11 // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12 // CONDITIONS OF ANY KIND, either express or implied. See the License for the
13 // specific language governing permissions and limitations under the License.
14
15 #include "unittest.h"
16
17 #include "rapidjson/allocators.h"
18
19 using namespace rapidjson;
20
21 template <typename Allocator>
TestAllocator(Allocator & a)22 void TestAllocator(Allocator& a) {
23 EXPECT_TRUE(a.Malloc(0) == 0);
24
25 uint8_t* p = (uint8_t*)a.Malloc(100);
26 EXPECT_TRUE(p != 0);
27 for (size_t i = 0; i < 100; i++)
28 p[i] = (uint8_t)i;
29
30 // Expand
31 uint8_t* q = (uint8_t*)a.Realloc(p, 100, 200);
32 EXPECT_TRUE(q != 0);
33 for (size_t i = 0; i < 100; i++)
34 EXPECT_EQ(i, q[i]);
35 for (size_t i = 100; i < 200; i++)
36 q[i] = (uint8_t)i;
37
38 // Shrink
39 uint8_t *r = (uint8_t*)a.Realloc(q, 200, 150);
40 EXPECT_TRUE(r != 0);
41 for (size_t i = 0; i < 150; i++)
42 EXPECT_EQ(i, r[i]);
43
44 Allocator::Free(r);
45
46 // Realloc to zero size
47 EXPECT_TRUE(a.Realloc(a.Malloc(1), 1, 0) == 0);
48 }
49
TEST(Allocator,CrtAllocator)50 TEST(Allocator, CrtAllocator) {
51 CrtAllocator a;
52 TestAllocator(a);
53 }
54
TEST(Allocator,MemoryPoolAllocator)55 TEST(Allocator, MemoryPoolAllocator) {
56 MemoryPoolAllocator<> a;
57 TestAllocator(a);
58
59 for (int i = 1; i < 1000; i++) {
60 EXPECT_TRUE(a.Malloc(i) != 0);
61 EXPECT_LE(a.Size(), a.Capacity());
62 }
63 }
64
TEST(Allocator,Alignment)65 TEST(Allocator, Alignment) {
66 #if RAPIDJSON_64BIT == 1
67 EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000000), RAPIDJSON_ALIGN(0));
68 for (uint64_t i = 1; i < 8; i++) {
69 EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000008), RAPIDJSON_ALIGN(i));
70 EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000010), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0x00000000, 0x00000008) + i));
71 EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000001, 0x00000000), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0x00000000, 0xFFFFFFF8) + i));
72 EXPECT_EQ(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFF8), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFF0) + i));
73 }
74 #else
75 EXPECT_EQ(0u, RAPIDJSON_ALIGN(0u));
76 for (uint32_t i = 1; i < 4; i++) {
77 EXPECT_EQ(4u, RAPIDJSON_ALIGN(i));
78 EXPECT_EQ(8u, RAPIDJSON_ALIGN(4u + i));
79 EXPECT_EQ(0xFFFFFFF8u, RAPIDJSON_ALIGN(0xFFFFFFF4u + i));
80 EXPECT_EQ(0xFFFFFFFCu, RAPIDJSON_ALIGN(0xFFFFFFF8u + i));
81 }
82 #endif
83 }
84