/src/brpc/src/butil/arena.h
Line | Count | Source |
1 | | // Licensed to the Apache Software Foundation (ASF) under one |
2 | | // or more contributor license agreements. See the NOTICE file |
3 | | // distributed with this work for additional information |
4 | | // regarding copyright ownership. The ASF licenses this file |
5 | | // to you under the Apache License, Version 2.0 (the |
6 | | // "License"); you may not use this file except in compliance |
7 | | // with the License. You may obtain a copy of the License at |
8 | | // |
9 | | // http://www.apache.org/licenses/LICENSE-2.0 |
10 | | // |
11 | | // Unless required by applicable law or agreed to in writing, |
12 | | // software distributed under the License is distributed on an |
13 | | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
14 | | // KIND, either express or implied. See the License for the |
15 | | // specific language governing permissions and limitations |
16 | | // under the License. |
17 | | |
18 | | // Date: Fri Jun 5 18:25:40 CST 2015 |
19 | | |
20 | | // Do small memory allocations on continuous blocks. |
21 | | |
22 | | #ifndef BUTIL_ARENA_H |
23 | | #define BUTIL_ARENA_H |
24 | | |
25 | | #include <stdint.h> |
26 | | #include "butil/macros.h" |
27 | | |
28 | | namespace butil { |
29 | | |
30 | | struct ArenaOptions { |
31 | | size_t initial_block_size; |
32 | | size_t max_block_size; |
33 | | |
34 | | // Constructed with default options. |
35 | | ArenaOptions(); |
36 | | }; |
37 | | |
38 | | // Just a proof-of-concept, will be refactored in future CI. |
39 | | class Arena { |
40 | | public: |
41 | | explicit Arena(const ArenaOptions& options = ArenaOptions()); |
42 | | ~Arena(); |
43 | | void swap(Arena&); |
44 | | void* allocate(size_t n); |
45 | | void* allocate_aligned(size_t n); // not implemented. |
46 | | void clear(); |
47 | | |
48 | | private: |
49 | | DISALLOW_COPY_AND_ASSIGN(Arena); |
50 | | |
51 | | struct Block { |
52 | 0 | uint32_t left_space() const { return size - alloc_size; } |
53 | | |
54 | | Block* next; |
55 | | uint32_t alloc_size; |
56 | | uint32_t size; |
57 | | char data[0]; |
58 | | }; |
59 | | |
60 | | void* allocate_in_other_blocks(size_t n); |
61 | | void* allocate_new_block(size_t n); |
62 | 0 | Block* pop_block(Block* & head) { |
63 | 0 | Block* saved_head = head; |
64 | 0 | head = head->next; |
65 | 0 | return saved_head; |
66 | 0 | } |
67 | | |
68 | | Block* _cur_block; |
69 | | Block* _isolated_blocks; |
70 | | size_t _block_size; |
71 | | ArenaOptions _options; |
72 | | }; |
73 | | |
74 | 0 | inline void* Arena::allocate(size_t n) { |
75 | 0 | if (_cur_block != NULL && _cur_block->left_space() >= n) { |
76 | 0 | void* ret = _cur_block->data + _cur_block->alloc_size; |
77 | 0 | _cur_block->alloc_size += n; |
78 | 0 | return ret; |
79 | 0 | } |
80 | 0 | return allocate_in_other_blocks(n); |
81 | 0 | } |
82 | | |
83 | | } // namespace butil |
84 | | |
85 | | #endif // BUTIL_ARENA_H |