10225501448 李度 10225101546 陈胤遒 10215501422 高宇菲
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

68 lignes
1.7 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 <vector>
  7. #include <assert.h>
  8. #include <stddef.h>
  9. #include <stdint.h>
  10. #include "port/port.h"
  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 reinterpret_cast<uintptr_t>(memory_usage_.NoBarrier_Load());
  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. port::AtomicPointer memory_usage_;
  35. // No copying allowed
  36. Arena(const Arena&);
  37. void operator=(const Arena&);
  38. };
  39. inline char* Arena::Allocate(size_t bytes) {
  40. // The semantics of what to return are a bit messy if we allow
  41. // 0-byte allocations, so we disallow them here (we don't need
  42. // them for our internal use).
  43. assert(bytes > 0);
  44. if (bytes <= alloc_bytes_remaining_) {
  45. char* result = alloc_ptr_;
  46. alloc_ptr_ += bytes;
  47. alloc_bytes_remaining_ -= bytes;
  48. return result;
  49. }
  50. return AllocateFallback(bytes);
  51. }
  52. } // namespace leveldb
  53. #endif // STORAGE_LEVELDB_UTIL_ARENA_H_