| 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 |
|
| |
| 5 |
|
| #ifndef STORAGE_LEVELDB_UTIL_ARENA_H_ |
| 6 |
|
| #define STORAGE_LEVELDB_UTIL_ARENA_H_ |
| 7 |
|
| |
| 8 |
|
| #include <cstddef> |
| 9 |
|
| #include <vector> |
| 10 |
|
| #include <assert.h> |
| 11 |
|
| #include <stdint.h> |
| 12 |
|
| |
| 13 |
|
| namespace leveldb { |
| 14 |
|
| |
| 15 |
|
| class Arena { |
| 16 |
|
| public: |
| 17 |
|
| Arena(); |
| 18 |
|
| ~Arena(); |
| 19 |
|
| |
| 20 |
|
| // Return a pointer to a newly allocated memory block of "bytes" bytes. |
| 21 |
|
| char* Allocate(size_t bytes); |
| 22 |
|
| |
| 23 |
|
| // Allocate memory with the normal alignment guarantees provided by malloc |
| 24 |
|
| char* AllocateAligned(size_t bytes); |
| 25 |
|
| |
| 26 |
|
| // Returns an estimate of the total memory usage of data allocated |
| 27 |
|
| // by the arena (including space allocated but not yet used for user |
| 28 |
|
| // allocations). |
| 29 |
31 |
| size_t MemoryUsage() const { |
| 30 |
31 |
| return blocks_memory_ + blocks_.capacity() * sizeof(char*); |
| 31 |
|
| } |
| 32 |
|
| |
| 33 |
|
| private: |
| 34 |
|
| char* AllocateFallback(size_t bytes); |
| 35 |
|
| char* AllocateNewBlock(size_t block_bytes); |
| 36 |
|
| |
| 37 |
|
| // Allocation state |
| 38 |
|
| char* alloc_ptr_; |
| 39 |
|
| size_t alloc_bytes_remaining_; |
| 40 |
|
| |
| 41 |
|
| // Array of new[] allocated memory blocks |
| 42 |
|
| std::vector<char*> blocks_; |
| 43 |
|
| |
| 44 |
|
| // Bytes of memory in blocks allocated so far |
| 45 |
|
| size_t blocks_memory_; |
| 46 |
|
| |
| 47 |
|
| // No copying allowed |
| 48 |
|
| Arena(const Arena&); |
| 49 |
|
| void operator=(const Arena&); |
| 50 |
|
| }; |
| 51 |
|
| |
| 52 |
31 |
| inline char* Arena::Allocate(size_t bytes) { |
| 53 |
|
| // The semantics of what to return are a bit messy if we allow |
| 54 |
|
| // 0-byte allocations, so we disallow them here (we don't need |
| 55 |
|
| // them for our internal use). |
| 56 |
31 |
▶ | assert(bytes > 0); |
Branch: 1 branch
| Branch | True | False | Total |
| assert(bytes > 0); |
0 |
31 |
31 |
|
| 57 |
31 |
▶ | if (bytes <= alloc_bytes_remaining_) { |
Branch: 1 branch
| Branch | True | False | Total |
| if (bytes <= alloc_bytes_remaining_) { |
31 |
0 |
31 |
|
| 58 |
31 |
| char* result = alloc_ptr_; |
| 59 |
31 |
| alloc_ptr_ += bytes; |
| 60 |
31 |
| alloc_bytes_remaining_ -= bytes; |
| 61 |
31 |
| return result; |
| 62 |
|
| } |
| 63 |
0 |
| return AllocateFallback(bytes); |
| 64 |
|
| } |
| 65 |
|
| |
| 66 |
|
| } |
| 67 |
|
| |
| 68 |
|
| #endif // STORAGE_LEVELDB_UTIL_ARENA_H_ |