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.8 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 <cstddef>
  7. #include <vector>
  8. #include <assert.h>
  9. #include <stdint.h>
  10. namespace leveldb {
  11. class Arena {
  12. public:
  13. Arena();
  14. ~Arena();
  15. // Return a pointer to a newly allocated memory block of "bytes" bytes.
  16. char* Allocate(size_t bytes);
  17. // Allocate memory with the normal alignment guarantees provided by malloc
  18. char* AllocateAligned(size_t bytes);
  19. // Returns an estimate of the total memory usage of data allocated
  20. // by the arena (including space allocated but not yet used for user
  21. // allocations).
  22. size_t MemoryUsage() const {
  23. return blocks_memory_ + blocks_.capacity() * sizeof(char*);
  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. // Bytes of memory in blocks allocated so far
  34. size_t blocks_memory_;
  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. }
  53. #endif // STORAGE_LEVELDB_UTIL_ARENA_H_