Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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