1 // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. See the AUTHORS file for names of contributors.
4
5 #include "util/arena.h"
6
7 #include "util/random.h"
8 #include "util/testharness.h"
9
10 namespace leveldb {
11
12 class ArenaTest { };
13
TEST(ArenaTest,Empty)14 TEST(ArenaTest, Empty) {
15 Arena arena;
16 }
17
TEST(ArenaTest,Simple)18 TEST(ArenaTest, Simple) {
19 std::vector<std::pair<size_t, char*> > allocated;
20 Arena arena;
21 const int N = 100000;
22 size_t bytes = 0;
23 Random rnd(301);
24 for (int i = 0; i < N; i++) {
25 size_t s;
26 if (i % (N / 10) == 0) {
27 s = i;
28 } else {
29 s = rnd.OneIn(4000) ? rnd.Uniform(6000) :
30 (rnd.OneIn(10) ? rnd.Uniform(100) : rnd.Uniform(20));
31 }
32 if (s == 0) {
33 // Our arena disallows size 0 allocations.
34 s = 1;
35 }
36 char* r;
37 if (rnd.OneIn(10)) {
38 r = arena.AllocateAligned(s);
39 } else {
40 r = arena.Allocate(s);
41 }
42
43 for (size_t b = 0; b < s; b++) {
44 // Fill the "i"th allocation with a known bit pattern
45 r[b] = i % 256;
46 }
47 bytes += s;
48 allocated.push_back(std::make_pair(s, r));
49 ASSERT_GE(arena.MemoryUsage(), bytes);
50 if (i > N/10) {
51 ASSERT_LE(arena.MemoryUsage(), bytes * 1.10);
52 }
53 }
54 for (size_t i = 0; i < allocated.size(); i++) {
55 size_t num_bytes = allocated[i].first;
56 const char* p = allocated[i].second;
57 for (size_t b = 0; b < num_bytes; b++) {
58 // Check the "i"th allocation for the known bit pattern
59 ASSERT_EQ(int(p[b]) & 0xff, i % 256);
60 }
61 }
62 }
63
64 } // namespace leveldb
65
main(int argc,char ** argv)66 int main(int argc, char** argv) {
67 return leveldb::test::RunAllTests();
68 }
69