Coverage Report

Created: 2025-07-11 07:01

/src/leveldb/util/arena.cc
Line
Count
Source (jump to first uncovered line)
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
186k
    : alloc_ptr_(nullptr), alloc_bytes_remaining_(0), memory_usage_(0) {}
13
14
186k
Arena::~Arena() {
15
408k
  for (size_t i = 0; i < blocks_.size(); i++) {
16
221k
    delete[] blocks_[i];
17
221k
  }
18
186k
}
19
20
221k
char* Arena::AllocateFallback(size_t bytes) {
21
221k
  if (bytes > kBlockSize / 4) {
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
6.24k
    char* result = AllocateNewBlock(bytes);
25
6.24k
    return result;
26
6.24k
  }
27
28
  // We waste the remaining space in the current block.
29
215k
  alloc_ptr_ = AllocateNewBlock(kBlockSize);
30
215k
  alloc_bytes_remaining_ = kBlockSize;
31
32
215k
  char* result = alloc_ptr_;
33
215k
  alloc_ptr_ += bytes;
34
215k
  alloc_bytes_remaining_ -= bytes;
35
215k
  return result;
36
221k
}
37
38
3.81M
char* Arena::AllocateAligned(size_t bytes) {
39
3.81M
  const int align = (sizeof(void*) > 8) ? sizeof(void*) : 8;
40
3.81M
  static_assert((align & (align - 1)) == 0,
41
3.81M
                "Pointer size should be a power of 2");
42
3.81M
  size_t current_mod = reinterpret_cast<uintptr_t>(alloc_ptr_) & (align - 1);
43
3.81M
  size_t slop = (current_mod == 0 ? 0 : align - current_mod);
44
3.81M
  size_t needed = bytes + slop;
45
3.81M
  char* result;
46
3.81M
  if (needed <= alloc_bytes_remaining_) {
47
3.61M
    result = alloc_ptr_ + slop;
48
3.61M
    alloc_ptr_ += needed;
49
3.61M
    alloc_bytes_remaining_ -= needed;
50
3.61M
  } else {
51
    // AllocateFallback always returned aligned memory
52
200k
    result = AllocateFallback(bytes);
53
200k
  }
54
3.81M
  assert((reinterpret_cast<uintptr_t>(result) & (align - 1)) == 0);
55
3.81M
  return result;
56
3.81M
}
57
58
221k
char* Arena::AllocateNewBlock(size_t block_bytes) {
59
221k
  char* result = new char[block_bytes];
60
221k
  blocks_.push_back(result);
61
221k
  memory_usage_.fetch_add(block_bytes + sizeof(char*),
62
221k
                          std::memory_order_relaxed);
63
221k
  return result;
64
221k
}
65
66
}  // namespace leveldb