/bitcoin/src/leveldb/util/arena.cc
Line | Count | Source |
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 | | #include "util/arena.h" |
6 | | |
7 | | namespace leveldb { |
8 | | |
9 | | static const int kBlockSize = 4096; |
10 | | |
11 | | Arena::Arena() |
12 | 33.3k | : alloc_ptr_(nullptr), alloc_bytes_remaining_(0), memory_usage_(0) {} |
13 | | |
14 | 33.3k | Arena::~Arena() { |
15 | 280k | for (size_t i = 0; i < blocks_.size(); i++) { Branch (15:22): [True: 247k, False: 33.3k]
|
16 | 247k | delete[] blocks_[i]; |
17 | 247k | } |
18 | 33.3k | } |
19 | | |
20 | 247k | char* Arena::AllocateFallback(size_t bytes) { |
21 | 247k | if (bytes > kBlockSize / 4) { Branch (21:7): [True: 0, False: 247k]
|
22 | | // Object is more than a quarter of our block size. Allocate it separately |
23 | | // to avoid wasting too much space in leftover bytes. |
24 | 0 | char* result = AllocateNewBlock(bytes); |
25 | 0 | return result; |
26 | 0 | } |
27 | | |
28 | | // We waste the remaining space in the current block. |
29 | 247k | alloc_ptr_ = AllocateNewBlock(kBlockSize); |
30 | 247k | alloc_bytes_remaining_ = kBlockSize; |
31 | | |
32 | 247k | char* result = alloc_ptr_; |
33 | 247k | alloc_ptr_ += bytes; |
34 | 247k | alloc_bytes_remaining_ -= bytes; |
35 | 247k | return result; |
36 | 247k | } |
37 | | |
38 | 6.96M | char* Arena::AllocateAligned(size_t bytes) { |
39 | 6.96M | const int align = (sizeof(void*) > 8) ? sizeof(void*) : 8; Branch (39:21): [Folded - Ignored]
|
40 | 6.96M | static_assert((align & (align - 1)) == 0, |
41 | 6.96M | "Pointer size should be a power of 2"); |
42 | 6.96M | size_t current_mod = reinterpret_cast<uintptr_t>(alloc_ptr_) & (align - 1); |
43 | 6.96M | size_t slop = (current_mod == 0 ? 0 : align - current_mod); Branch (43:18): [True: 777k, False: 6.19M]
|
44 | 6.96M | size_t needed = bytes + slop; |
45 | 6.96M | char* result; |
46 | 6.96M | if (needed <= alloc_bytes_remaining_) { Branch (46:7): [True: 6.90M, False: 65.9k]
|
47 | 6.90M | result = alloc_ptr_ + slop; |
48 | 6.90M | alloc_ptr_ += needed; |
49 | 6.90M | alloc_bytes_remaining_ -= needed; |
50 | 6.90M | } else { |
51 | | // AllocateFallback always returned aligned memory |
52 | 65.9k | result = AllocateFallback(bytes); |
53 | 65.9k | } |
54 | 6.96M | assert((reinterpret_cast<uintptr_t>(result) & (align - 1)) == 0); Branch (54:3): [True: 6.96M, False: 0]
|
55 | 6.96M | return result; |
56 | 6.96M | } |
57 | | |
58 | 247k | char* Arena::AllocateNewBlock(size_t block_bytes) { |
59 | 247k | char* result = new char[block_bytes]; |
60 | 247k | blocks_.push_back(result); |
61 | 247k | memory_usage_.fetch_add(block_bytes + sizeof(char*), |
62 | 247k | std::memory_order_relaxed); |
63 | 247k | return result; |
64 | 247k | } |
65 | | |
66 | | } // namespace leveldb |