10225501448 李度 10225101546 陈胤遒 10215501422 高宇菲
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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