10225501448 李度 10225101546 陈胤遒 10215501422 高宇菲
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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