arena.cc 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. namespace leveldb {
  6. static const int kBlockSize = 4096;
  7. Arena::Arena()
  8. : alloc_ptr_(nullptr), alloc_bytes_remaining_(0), memory_usage_(0) {}
  9. Arena::~Arena() {
  10. for (size_t i = 0; i < blocks_.size(); i++) {
  11. delete[] blocks_[i];
  12. }
  13. }
  14. char* Arena::AllocateFallback(size_t bytes) {
  15. if (bytes > kBlockSize / 4) {
  16. // Object is more than a quarter of our block size. Allocate it separately
  17. // to avoid wasting too much space in leftover bytes.
  18. char* result = AllocateNewBlock(bytes);
  19. return result;
  20. }
  21. // We waste the remaining space in the current block.
  22. alloc_ptr_ = AllocateNewBlock(kBlockSize);
  23. alloc_bytes_remaining_ = kBlockSize;
  24. char* result = alloc_ptr_;
  25. alloc_ptr_ += bytes;
  26. alloc_bytes_remaining_ -= bytes;
  27. return result;
  28. }
  29. char* Arena::AllocateAligned(size_t bytes) {
  30. const int align = (sizeof(void*) > 8) ? sizeof(void*) : 8;
  31. static_assert((align & (align - 1)) == 0,
  32. "Pointer size should be a power of 2");
  33. size_t current_mod = reinterpret_cast<uintptr_t>(alloc_ptr_) & (align - 1);
  34. size_t slop = (current_mod == 0 ? 0 : align - current_mod);
  35. size_t needed = bytes + slop;
  36. char* result;
  37. if (needed <= alloc_bytes_remaining_) {
  38. result = alloc_ptr_ + slop;
  39. alloc_ptr_ += needed;
  40. alloc_bytes_remaining_ -= needed;
  41. } else {
  42. // AllocateFallback always returned aligned memory
  43. result = AllocateFallback(bytes);
  44. }
  45. assert((reinterpret_cast<uintptr_t>(result) & (align - 1)) == 0);
  46. return result;
  47. }
  48. char* Arena::AllocateNewBlock(size_t block_bytes) {
  49. char* result = new char[block_bytes];
  50. blocks_.push_back(result);
  51. memory_usage_.fetch_add(block_bytes + sizeof(char*),
  52. std::memory_order_relaxed);
  53. return result;
  54. }
  55. } // namespace leveldb