MiniOB 1
MiniOB is one mini database, helping developers to learn how database works.
载入中...
搜索中...
未找到
arena_allocator.h
1/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
2miniob is licensed under Mulan PSL v2.
3You can use this software according to the terms and conditions of the Mulan PSL v2.
4You may obtain a copy of Mulan PSL v2 at:
5 http://license.coscl.org.cn/MulanPSL2
6THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
7EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
8MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
9See the Mulan PSL v2 for more details. */
10
11// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
12// Use of this source code is governed by a BSD-style license that can be
13// found in the LICENSE file. See the AUTHORS file for names of contributors.
14
15#pragma once
16
17#include <atomic>
18#include <cassert>
19#include <cstddef>
20#include <cstdint>
21#include <vector>
22
23class Arena
24{
25public:
26 Arena();
27
28 Arena(const Arena &) = delete;
29 Arena &operator=(const Arena &) = delete;
30
31 ~Arena();
32
33 // Return a pointer to a newly allocated memory block of "bytes" bytes.
34 char *Allocate(size_t bytes);
35
36 // Allocate memory with the normal alignment guarantees provided by malloc.
37 char *AllocateAligned(size_t bytes);
38
39 // Returns an estimate of the total memory usage of data allocated
40 // by the arena.
41 size_t MemoryUsage() const { return memory_usage_.load(std::memory_order_relaxed); }
42
43private:
44 char *AllocateFallback(size_t bytes);
45 char *AllocateNewBlock(size_t block_bytes);
46
47 // Allocation state
48 char *alloc_ptr_;
49 size_t alloc_bytes_remaining_;
50
51 // Array of new[] allocated memory blocks
52 std::vector<char *> blocks_;
53
54 // Total memory usage of the arena.
55 //
56 // TODO(costan): This member is accessed via atomics, but the others are
57 // accessed without any locking. Is this OK?
58 std::atomic<size_t> memory_usage_;
59};
60
61inline char *Arena::Allocate(size_t bytes)
62{
63 // The semantics of what to return are a bit messy if we allow
64 // 0-byte allocations, so we disallow them here (we don't need
65 // them for our internal use).
66 assert(bytes > 0);
67 if (bytes <= alloc_bytes_remaining_) {
68 char *result = alloc_ptr_;
69 alloc_ptr_ += bytes;
70 alloc_bytes_remaining_ -= bytes;
71 return result;
72 }
73 return AllocateFallback(bytes);
74}
Definition: arena_allocator.h:24