arena.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. #ifndef STORAGE_LEVELDB_UTIL_ARENA_H_
  5. #define STORAGE_LEVELDB_UTIL_ARENA_H_
  6. #include <atomic>
  7. #include <cassert>
  8. #include <cstddef>
  9. #include <cstdint>
  10. #include <vector>
  11. namespace leveldb {
  12. class Arena {
  13. public:
  14. Arena();
  15. Arena(const Arena&) = delete;
  16. Arena& operator=(const Arena&) = delete;
  17. ~Arena();
  18. // Return a pointer to a newly allocated memory block of "bytes" bytes.
  19. char* Allocate(size_t bytes);
  20. // Allocate memory with the normal alignment guarantees provided by malloc.
  21. char* AllocateAligned(size_t bytes);
  22. // Returns an estimate of the total memory usage of data allocated
  23. // by the arena.
  24. size_t MemoryUsage() const {
  25. return memory_usage_.load(std::memory_order_relaxed);
  26. }
  27. private:
  28. char* AllocateFallback(size_t bytes);
  29. char* AllocateNewBlock(size_t block_bytes);
  30. // Allocation state
  31. char* alloc_ptr_;
  32. size_t alloc_bytes_remaining_;
  33. // Array of new[] allocated memory blocks
  34. std::vector<char*> blocks_;
  35. // Total memory usage of the arena.
  36. //
  37. // TODO(costan): This member is accessed via atomics, but the others are
  38. // accessed without any locking. Is this OK?
  39. std::atomic<size_t> memory_usage_;
  40. };
  41. inline char* Arena::Allocate(size_t bytes) {
  42. // The semantics of what to return are a bit messy if we allow
  43. // 0-byte allocations, so we disallow them here (we don't need
  44. // them for our internal use).
  45. assert(bytes > 0);
  46. if (bytes <= alloc_bytes_remaining_) {
  47. char* result = alloc_ptr_;
  48. alloc_ptr_ += bytes;
  49. alloc_bytes_remaining_ -= bytes;
  50. return result;
  51. }
  52. return AllocateFallback(bytes);
  53. }
  54. } // namespace leveldb
  55. #endif // STORAGE_LEVELDB_UTIL_ARENA_H_