/ src / leveldb / util / arena_test.cc
arena_test.cc
 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  
14  TEST(ArenaTest, Empty) { Arena arena; }
15  
16  TEST(ArenaTest, Simple) {
17    std::vector<std::pair<size_t, char*>> allocated;
18    Arena arena;
19    const int N = 100000;
20    size_t bytes = 0;
21    Random rnd(301);
22    for (int i = 0; i < N; i++) {
23      size_t s;
24      if (i % (N / 10) == 0) {
25        s = i;
26      } else {
27        s = rnd.OneIn(4000)
28                ? rnd.Uniform(6000)
29                : (rnd.OneIn(10) ? rnd.Uniform(100) : rnd.Uniform(20));
30      }
31      if (s == 0) {
32        // Our arena disallows size 0 allocations.
33        s = 1;
34      }
35      char* r;
36      if (rnd.OneIn(10)) {
37        r = arena.AllocateAligned(s);
38      } else {
39        r = arena.Allocate(s);
40      }
41  
42      for (size_t b = 0; b < s; b++) {
43        // Fill the "i"th allocation with a known bit pattern
44        r[b] = i % 256;
45      }
46      bytes += s;
47      allocated.push_back(std::make_pair(s, r));
48      ASSERT_GE(arena.MemoryUsage(), bytes);
49      if (i > N / 10) {
50        ASSERT_LE(arena.MemoryUsage(), bytes * 1.10);
51      }
52    }
53    for (size_t i = 0; i < allocated.size(); i++) {
54      size_t num_bytes = allocated[i].first;
55      const char* p = allocated[i].second;
56      for (size_t b = 0; b < num_bytes; b++) {
57        // Check the "i"th allocation for the known bit pattern
58        ASSERT_EQ(int(p[b]) & 0xff, i % 256);
59      }
60    }
61  }
62  
63  }  // namespace leveldb
64  
65  int main(int argc, char** argv) { return leveldb::test::RunAllTests(); }