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