arena_test.cc 1.6 KB

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