SPH
MemoryPool.h
Go to the documentation of this file.
1 #pragma once
2 
4 
5 namespace Sph {
6 
7 template <typename T, int ChunkSize>
8 class MemoryPool : public Noncopyable {
9  typedef Array<T> Chunk;
10  Array<Chunk> chunks;
11  Size pos = 0;
12 
13 public:
14  MemoryPool() = default;
15 
16  ArrayView<T> alloc(const Size n) {
17  ASSERT(n < ChunkSize);
18  if (pos + n > size()) {
19  pos = size() + n;
20  chunks.emplaceBack(ChunkSize);
21  return ArrayView<T>(&chunks.back()[0], n);
22  } else {
23  int posInChunk = pos - (size() - ChunkSize);
24  T& data = chunks.back()[posInChunk];
25  pos += n;
26  return ArrayView<T>(&data, n);
27  }
28  }
29 
30  void clear() {
31  chunks.clear();
32  pos = 0;
33  }
34 
35  Size size() const {
36  return chunks.size() * ChunkSize;
37  }
38 };
39 
40 
41 } // namespace Sph
Generic dynamically allocated resizable storage.
uint32_t Size
Integral type used to index arrays (by default).
Definition: Globals.h:16
Object providing safe access to continuous memory of data.
Definition: ArrayView.h:17
Generic dynamically allocated resizable storage.
Definition: Array.h:43
StorageType & emplaceBack(TArgs &&... args)
Constructs a new element at the end of the array in place, using the provided arguments.
Definition: Array.h:332
INLINE T & back() noexcept
Definition: Array.h:176
void clear()
Removes all elements from the array, but does NOT release the memory.
Definition: Array.h:434
INLINE TCounter size() const noexcept
Definition: Array.h:193
Size size() const
Definition: MemoryPool.h:35
ArrayView< T > alloc(const Size n)
Definition: MemoryPool.h:16
MemoryPool()=default
Definition: MemoryPool.h:5
Object with deleted copy constructor and copy operator.
Definition: Object.h:54