Belle II Software light-2406-ragdoll
MemoryPool.h
1/**************************************************************************
2 * basf2 (Belle II Analysis Software Framework) *
3 * Author: The Belle II Collaboration *
4 * *
5 * See git log for contributors and copyright holders. *
6 * This file is licensed under LGPL-3.0, see LICENSE.md. *
7 **************************************************************************/
8
9#pragma once
10
11#include <vector>
12#include <cstddef>
13#include <cstdlib>
14
15namespace Belle2 {
33 template < class T, int chunkSize = 128 > class MemoryPool {
34
35 public:
40 explicit MemoryPool(int n = 0): m_entries(0) { reserve(n); }
41
44
49 size_t size() const { return m_entries; }
50
56 T* operator[](size_t i) { return m_chunks[i / chunkSize] + i % chunkSize; }
57
63 T* at(size_t i) { return (i >= m_entries) ? 0 : (*this)[i]; }
64
68 void clear() { m_entries = 0; }
69
74 T* add()
75 {
76 if (m_entries / chunkSize >= m_chunks.size()) {
77 m_chunks.push_back(reinterpret_cast<T*>(malloc(chunkSize * sizeof(T))));
78 }
79 return (*this)[m_entries++];
80 }
81
86 void reserve(size_t n)
87 {
88 size_t needed_chunks = n / chunkSize + 1;
89 m_chunks.reserve(needed_chunks);
90 while (m_chunks.size() < needed_chunks) {
91 m_chunks.push_back(reinterpret_cast<T*>(malloc(chunkSize * sizeof(T))));
92 }
93 }
94
99 {
100 for (T* ptr : m_chunks) {
101 free(reinterpret_cast<void*>(ptr));
102 }
103 m_chunks.clear();
104 }
105
106 protected:
107
108 size_t m_entries;
109 std::vector<T*> m_chunks;
110 };
111
113} //end namespace Belle2
Class to provide a constant access time memory pool for one kind of objects.
Definition: MemoryPool.h:33
~MemoryPool()
Free allocated memory.
Definition: MemoryPool.h:43
MemoryPool(int n=0)
Constructor.
Definition: MemoryPool.h:40
size_t size() const
Return number of elements currently stored.
Definition: MemoryPool.h:49
T * at(size_t i)
Return pointer to memory segment for element i, including range check.
Definition: MemoryPool.h:63
void release_memory()
Release all allocated memory, called automatically upon destruction.
Definition: MemoryPool.h:98
T * add()
Returns an pointer to the next free memory segment, allocating additional memory if necessary.
Definition: MemoryPool.h:74
void clear()
Clear number of entries, does not free memory or call destructors.
Definition: MemoryPool.h:68
std::vector< T * > m_chunks
Pointers to all allocated memory chunks.
Definition: MemoryPool.h:109
T * operator[](size_t i)
Return pointer to memory segment for element i, no range check.
Definition: MemoryPool.h:56
void reserve(size_t n)
Make sure there is enough memory allocated for n elements.
Definition: MemoryPool.h:86
size_t m_entries
Number of occupied entries.
Definition: MemoryPool.h:108
Abstract base class for different kinds of events.
Definition: ClusterUtils.h:24