File: memory_pool.hpp

package info (click to toggle)
foonathan-memory 0.7.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,644 kB
  • sloc: cpp: 12,425; xml: 139; sh: 48; makefile: 25
file content (438 lines) | stat: -rw-r--r-- 22,578 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// Copyright (C) 2015-2025 Jonathan Müller and foonathan/memory contributors
// SPDX-License-Identifier: Zlib

#ifndef FOONATHAN_MEMORY_MEMORY_POOL_HPP_INCLUDED
#define FOONATHAN_MEMORY_MEMORY_POOL_HPP_INCLUDED

// Inform that foonathan::memory::memory_pool::min_block_size API is available
#define FOONATHAN_MEMORY_MEMORY_POOL_HAS_MIN_BLOCK_SIZE

/// \file
/// Class \ref foonathan::memory::memory_pool and its \ref foonathan::memory::allocator_traits specialization.

#include <type_traits>

#include "detail/align.hpp"
#include "detail/debug_helpers.hpp"
#include "detail/assert.hpp"
#include "config.hpp"
#include "error.hpp"
#include "memory_arena.hpp"
#include "memory_pool_type.hpp"

namespace foonathan
{
    namespace memory
    {
        namespace detail
        {
            struct memory_pool_leak_handler
            {
                void operator()(std::ptrdiff_t amount);
            };
        } // namespace detail

        /// A stateful \concept{concept_rawallocator,RawAllocator} that manages \concept{concept_node,nodes} of fixed size.
        /// It uses a \ref memory_arena with a given \c BlockOrRawAllocator defaulting to \ref growing_block_allocator,
        /// subdivides them in small nodes of given size and puts them onto a free list.
        /// Allocation and deallocation simply remove or add nodes from this list and are thus fast.
        /// The way the list is maintained can be controlled via the \c PoolType
        /// which is either \ref node_pool, \ref array_pool or \ref small_node_pool.<br>
        /// This kind of allocator is ideal for fixed size allocations and deallocations in any order,
        /// for example in a node based container like \c std::list.
        /// It is not so good for different allocation sizes and has some drawbacks for arrays
        /// as described in \ref memory_pool_type.hpp.
        /// \ingroup allocator
        template <typename PoolType = node_pool, class BlockOrRawAllocator = default_allocator>
        class memory_pool
        : FOONATHAN_EBO(detail::default_leak_checker<detail::memory_pool_leak_handler>)
        {
            using free_list    = typename PoolType::type;
            using leak_checker = detail::default_leak_checker<detail::memory_pool_leak_handler>;

        public:
            using allocator_type = make_block_allocator_t<BlockOrRawAllocator>;
            using pool_type      = PoolType;

            static constexpr std::size_t min_node_size =
                FOONATHAN_IMPL_DEFINED(free_list::min_element_size);

            /// \returns The minimum block size required for certain number of \concept{concept_node,node}.
            /// \requires \c node_size must be a valid \concept{concept_node,node size}
            /// and \c number_of_nodes must be a non-zero value.
            /// \note MSVC's implementation of \c std::list for example is never empty and always allocates proxy nodes.
            /// To get enough memory for \c N elements of a list, \c number_of_nodes needs to include the proxy count in addition to \c N.
            static constexpr std::size_t min_block_size(std::size_t node_size,
                                                        std::size_t number_of_nodes) noexcept
            {
                return detail::memory_block_stack::implementation_offset()
                       + free_list::min_block_size(node_size, number_of_nodes);
            }

            /// \effects Creates it by specifying the size each \concept{concept_node,node} will have,
            /// the initial block size for the arena and other constructor arguments for the \concept{concept_blockallocator,BlockAllocator}.
            /// If the \c node_size is less than the \c min_node_size, the \c min_node_size will be the actual node size.
            /// It will allocate an initial memory block with given size from the \concept{concept_blockallocator,BlockAllocator}
            /// and puts it onto the free list.
            /// \requires \c node_size must be a valid \concept{concept_node,node size}
            /// and \c block_size must be at least \c min_block_size(node_size, 1).
            template <typename... Args>
            memory_pool(std::size_t node_size, std::size_t block_size, Args&&... args)
            : arena_(block_size, detail::forward<Args>(args)...), free_list_(node_size)
            {
                allocate_block();
            }

            /// \effects Destroys the \ref memory_pool by returning all memory blocks,
            /// regardless of properly deallocated back to the \concept{concept_blockallocator,BlockAllocator}.
            ~memory_pool() noexcept {}

            /// @{
            /// \effects Moving a \ref memory_pool object transfers ownership over the free list,
            /// i.e. the moved from pool is completely empty and the new one has all its memory.
            /// That means that it is not allowed to call \ref deallocate_node() on a moved-from allocator
            /// even when passing it memory that was previously allocated by this object.
            memory_pool(memory_pool&& other) noexcept
            : leak_checker(detail::move(other)),
              arena_(detail::move(other.arena_)),
              free_list_(detail::move(other.free_list_))
            {
            }

            memory_pool& operator=(memory_pool&& other) noexcept
            {
                leak_checker::operator=(detail::move(other));
                arena_     = detail::move(other.arena_);
                free_list_ = detail::move(other.free_list_);
                return *this;
            }
            /// @}

            /// \effects Allocates a single \concept{concept_node,node} by removing it from the free list.
            /// If the free list is empty, a new memory block will be allocated from the arena and put onto it.
            /// The new block size will be \ref next_capacity() big.
            /// \returns A node of size \ref node_size() suitable aligned,
            /// i.e. suitable for any type where <tt>sizeof(T) < node_size()</tt>.
            /// \throws Anything thrown by the used \concept{concept_blockallocator,BlockAllocator}'s allocation function if a growth is needed.
            void* allocate_node()
            {
                if (free_list_.empty())
                    allocate_block();
                FOONATHAN_MEMORY_ASSERT(!free_list_.empty());
                return free_list_.allocate();
            }

            /// \effects Allocates a single \concept{concept_node,node} similar to \ref allocate_node().
            /// But if the free list is empty, a new block will *not* be allocated.
            /// \returns A suitable aligned node of size \ref node_size() or `nullptr`.
            void* try_allocate_node() noexcept
            {
                return free_list_.empty() ? nullptr : free_list_.allocate();
            }

            /// \effects Allocates an \concept{concept_array,array} of nodes by searching for \c n continuous nodes on the list and removing them.
            /// Depending on the \c PoolType this can be a slow operation or not allowed at all.
            /// This can sometimes lead to a growth, even if technically there is enough continuous memory on the free list.
            /// \returns An array of \c n nodes of size \ref node_size() suitable aligned.
            /// \throws Anything thrown by the used \concept{concept_blockallocator,BlockAllocator}'s allocation function if a growth is needed,
            /// or \ref bad_array_size if <tt>n * node_size()</tt> is too big.
            /// \requires \c n must be valid \concept{concept_array,array count}.
            void* allocate_array(std::size_t n)
            {
                detail::check_allocation_size<bad_array_size>(
                    n * node_size(), [&] { return pool_type::value ? next_capacity() : 0; },
                    info());
                return allocate_array(n, node_size());
            }

            /// \effects Allocates an \concept{concept_array,array} of nodes similar to \ref allocate_array().
            /// But it will never allocate a new memory block.
            /// \returns An array of \c n nodes of size \ref node_size() suitable aligned
            /// or `nullptr`.
            void* try_allocate_array(std::size_t n) noexcept
            {
                return try_allocate_array(n, node_size());
            }

            /// \effects Deallocates a single \concept{concept_node,node} by putting it back onto the free list.
            /// \requires \c ptr must be a result from a previous call to \ref allocate_node() on the same free list,
            /// i.e. either this allocator object or a new object created by moving this to it.
            void deallocate_node(void* ptr) noexcept
            {
                free_list_.deallocate(ptr);
            }

            /// \effects Deallocates a single \concept{concept_node,node} but it does not be a result of a previous call to \ref allocate_node().
            /// \returns `true` if the node could be deallocated, `false` otherwise.
            /// \note Some free list implementations can deallocate any memory,
            /// doesn't matter where it is coming from.
            bool try_deallocate_node(void* ptr) noexcept
            {
                if (!arena_.owns(ptr))
                    return false;
                free_list_.deallocate(ptr);
                return true;
            }

            /// \effects Deallocates an \concept{concept_array,array} by putting it back onto the free list.
            /// \requires \c ptr must be a result from a previous call to \ref allocate_array() with the same \c n on the same free list,
            /// i.e. either this allocator object or a new object created by moving this to it.
            void deallocate_array(void* ptr, std::size_t n) noexcept
            {
                FOONATHAN_MEMORY_ASSERT_MSG(pool_type::value, "does not support array allocations");
                free_list_.deallocate(ptr, n * node_size());
            }

            /// \effects Deallocates an \concept{concept_array,array} but it does not be a result of a previous call to \ref allocate_array().
            /// \returns `true` if the node could be deallocated, `false` otherwise.
            /// \note Some free list implementations can deallocate any memory,
            /// doesn't matter where it is coming from.
            bool try_deallocate_array(void* ptr, std::size_t n) noexcept
            {
                return try_deallocate_array(ptr, n, node_size());
            }

            /// \returns The size of each \concept{concept_node,node} in the pool,
            /// this is either the same value as in the constructor or \c min_node_size if the value was too small.
            std::size_t node_size() const noexcept
            {
                return free_list_.node_size();
            }

            /// \effects Returns the total amount of bytes remaining on the free list.
            /// Divide it by \ref node_size() to get the number of nodes that can be allocated without growing the arena.
            /// \note Array allocations may lead to a growth even if the capacity_left left is big enough.
            std::size_t capacity_left() const noexcept
            {
                return free_list_.capacity() * node_size();
            }

            /// \returns The size of the next memory block after the free list gets empty and the arena grows.
            /// \ref capacity_left() will increase by this amount.
            /// \note Due to fence memory in debug mode this cannot be just divided by the \ref node_size() to get the number of nodes.
            std::size_t next_capacity() const noexcept
            {
                return free_list_.usable_size(arena_.next_block_size());
            }

            /// \returns A reference to the \concept{concept_blockallocator,BlockAllocator} used for managing the arena.
            /// \requires It is undefined behavior to move this allocator out into another object.
            allocator_type& get_allocator() noexcept
            {
                return arena_.get_allocator();
            }

            /// \returns If `ptr` is in memory owned by the underlying arena.
            bool owns(const void* ptr) const noexcept
            {
                return arena_.owns(ptr);
            }

        private:
            allocator_info info() const noexcept
            {
                return {FOONATHAN_MEMORY_LOG_PREFIX "::memory_pool", this};
            }

            void allocate_block()
            {
                auto mem = arena_.allocate_block();
                free_list_.insert(static_cast<char*>(mem.memory), mem.size);
            }

            void* allocate_array(std::size_t n, std::size_t node_size)
            {
                auto mem = free_list_.empty() ? nullptr : free_list_.allocate(n * node_size);
                if (!mem)
                {
                    allocate_block();
                    mem = free_list_.allocate(n * node_size);
                    if (!mem)
                        FOONATHAN_THROW(bad_array_size(info(), n * node_size, capacity_left()));
                }
                return mem;
            }

            void* try_allocate_array(std::size_t n, std::size_t node_size) noexcept
            {
                return !pool_type::value || free_list_.empty() ? nullptr :
                                                                 free_list_.allocate(n * node_size);
            }

            bool try_deallocate_array(void* ptr, std::size_t n, std::size_t node_size) noexcept
            {
                if (!pool_type::value || !arena_.owns(ptr))
                    return false;
                free_list_.deallocate(ptr, n * node_size);
                return true;
            }

            memory_arena<allocator_type, false> arena_;
            free_list                           free_list_;

            friend allocator_traits<memory_pool<PoolType, BlockOrRawAllocator>>;
            friend composable_allocator_traits<memory_pool<PoolType, BlockOrRawAllocator>>;
        };

#if FOONATHAN_MEMORY_EXTERN_TEMPLATE
        extern template class memory_pool<node_pool>;
        extern template class memory_pool<array_pool>;
        extern template class memory_pool<small_node_pool>;
#endif

        template <class Type, class Alloc>
        constexpr std::size_t memory_pool<Type, Alloc>::min_node_size;

        /// Specialization of the \ref allocator_traits for \ref memory_pool classes.
        /// \note It is not allowed to mix calls through the specialization and through the member functions,
        /// i.e. \ref memory_pool::allocate_node() and this \c allocate_node().
        /// \ingroup allocator
        template <typename PoolType, class ImplRawAllocator>
        class allocator_traits<memory_pool<PoolType, ImplRawAllocator>>
        {
        public:
            using allocator_type = memory_pool<PoolType, ImplRawAllocator>;
            using is_stateful    = std::true_type;

            /// \returns The result of \ref memory_pool::allocate_node().
            /// \throws Anything thrown by the pool allocation function
            /// or a \ref bad_allocation_size exception.
            static void* allocate_node(allocator_type& state, std::size_t size,
                                       std::size_t alignment)
            {
                detail::check_allocation_size<bad_node_size>(size, max_node_size(state),
                                                             state.info());
                detail::check_allocation_size<
                    bad_alignment>(alignment, [&] { return max_alignment(state); }, state.info());
                auto mem = state.allocate_node();
                state.on_allocate(size);
                return mem;
            }

            /// \effects Forwards to \ref memory_pool::allocate_array()
            /// with the number of nodes adjusted to be the minimum,
            /// i.e. when the \c size is less than the \ref memory_pool::node_size().
            /// \returns A \concept{concept_array,array} with specified properties.
            /// \requires The \ref memory_pool has to support array allocations.
            /// \throws Anything thrown by the pool allocation function.
            static void* allocate_array(allocator_type& state, std::size_t count, std::size_t size,
                                        std::size_t alignment)
            {
                detail::check_allocation_size<bad_node_size>(size, max_node_size(state),
                                                             state.info());
                detail::check_allocation_size<
                    bad_alignment>(alignment, [&] { return max_alignment(state); }, state.info());
                detail::check_allocation_size<bad_array_size>(count * size, max_array_size(state),
                                                              state.info());
                auto mem = state.allocate_array(count, size);
                state.on_allocate(count * size);
                return mem;
            }

            /// \effects Just forwards to \ref memory_pool::deallocate_node().
            static void deallocate_node(allocator_type& state, void* node, std::size_t size,
                                        std::size_t) noexcept
            {
                state.deallocate_node(node);
                state.on_deallocate(size);
            }

            /// \effects Forwards to \ref memory_pool::deallocate_array() with the same size adjustment.
            static void deallocate_array(allocator_type& state, void* array, std::size_t count,
                                         std::size_t size, std::size_t) noexcept
            {
                state.free_list_.deallocate(array, count * size);
                state.on_deallocate(count * size);
            }

            /// \returns The maximum size of each node which is \ref memory_pool::node_size().
            static std::size_t max_node_size(const allocator_type& state) noexcept
            {
                return state.node_size();
            }

            /// \returns An upper bound on the maximum array size which is \ref memory_pool::next_capacity().
            static std::size_t max_array_size(const allocator_type& state) noexcept
            {
                return state.next_capacity();
            }

            /// \returns The maximum alignment which is the next bigger power of two if less than \c alignof(std::max_align_t)
            /// or the maximum alignment itself otherwise.
            static std::size_t max_alignment(const allocator_type& state) noexcept
            {
                return state.free_list_.alignment();
            }
        };

        /// Specialization of the \ref composable_allocator_traits for \ref memory_pool classes.
        /// \ingroup allocator
        template <typename PoolType, class BlockOrRawAllocator>
        class composable_allocator_traits<memory_pool<PoolType, BlockOrRawAllocator>>
        {
            using traits = allocator_traits<memory_pool<PoolType, BlockOrRawAllocator>>;

        public:
            using allocator_type = memory_pool<PoolType, BlockOrRawAllocator>;

            /// \returns The result of \ref memory_pool::try_allocate_node()
            /// or `nullptr` if the allocation size was too big.
            static void* try_allocate_node(allocator_type& state, std::size_t size,
                                           std::size_t alignment) noexcept
            {
                if (size > traits::max_node_size(state) || alignment > traits::max_alignment(state))
                    return nullptr;
                return state.try_allocate_node();
            }

            /// \effects Forwards to \ref memory_pool::try_allocate_array()
            /// with the number of nodes adjusted to be the minimum,
            /// if the \c size is less than the \ref memory_pool::node_size().
            /// \returns A \concept{concept_array,array} with specified properties
            /// or `nullptr` if it was unable to allocate.
            static void* try_allocate_array(allocator_type& state, std::size_t count,
                                            std::size_t size, std::size_t alignment) noexcept
            {
                if (size > traits::max_node_size(state)
                    || count * size > traits::max_array_size(state)
                    || alignment > traits::max_alignment(state))
                    return nullptr;
                return state.try_allocate_array(count, size);
            }

            /// \effects Just forwards to \ref memory_pool::try_deallocate_node().
            /// \returns Whether the deallocation was successful.
            static bool try_deallocate_node(allocator_type& state, void* node, std::size_t size,
                                            std::size_t alignment) noexcept
            {
                if (size > traits::max_node_size(state) || alignment > traits::max_alignment(state))
                    return false;
                return state.try_deallocate_node(node);
            }

            /// \effects Forwards to \ref memory_pool::deallocate_array() with the same size adjustment.
            /// \returns Whether the deallocation was successful.
            static bool try_deallocate_array(allocator_type& state, void* array, std::size_t count,
                                             std::size_t size, std::size_t alignment) noexcept
            {
                if (size > traits::max_node_size(state)
                    || count * size > traits::max_array_size(state)
                    || alignment > traits::max_alignment(state))
                    return false;
                return state.try_deallocate_array(array, count, size);
            }
        };

#if FOONATHAN_MEMORY_EXTERN_TEMPLATE
        extern template class allocator_traits<memory_pool<node_pool>>;
        extern template class allocator_traits<memory_pool<array_pool>>;
        extern template class allocator_traits<memory_pool<small_node_pool>>;

        extern template class composable_allocator_traits<memory_pool<node_pool>>;
        extern template class composable_allocator_traits<memory_pool<array_pool>>;
        extern template class composable_allocator_traits<memory_pool<small_node_pool>>;
#endif
    } // namespace memory
} // namespace foonathan

#endif // FOONATHAN_MEMORY_MEMORY_POOL_HPP_INCLUDED