作者: 谢瑞阳 10225101483 徐翔宇 10225101535
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.7 KiB

  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
  55. int main(int argc, char** argv) {
  56. testing::InitGoogleTest(&argc, argv);
  57. return RUN_ALL_TESTS();
  58. }