Flow
Documentation for the Flow C++ Library
Loading...
Searching...
No Matches
flow_pool_memory_resource.h
Go to the documentation of this file.
1#pragma once
4#include <cstddef>
5#include <exception>
6
7namespace flow {
8
15 public:
16 PoolMemoryResource(void* buffer, std::size_t capacity, std::size_t blockSize, std::size_t blockAlignment = sizeof(std::max_align_t))
17 : blockSize_(blockSize), blockAlignment_(blockAlignment), head_(nullptr) {
18
19 Header** headPtr = &head_;
20 for (;;) {
21 Header* header = alignWithHeader<Header>(blockAlignment_, blockSize_, buffer, capacity);
22 if (!header) {
23 break;
24 }
25
26 new (header) Header(nullptr);
27 *headPtr = header;
28 headPtr = &(header->next);
29
30 buffer = reinterpret_cast<std::byte*>(buffer) + sizeof(Header) + blockSize;
31 capacity -= sizeof(Header) + blockSize;
32 }
33 }
34
36 // May be useless, since it has a trivial destructor.
37 while (head_) {
38 Header* next = head_->next;
39 head_->~Header();
40 head_ = next;
41 }
42 }
43
44 protected:
45 struct Header {
47 };
48
49 std::size_t blockSize_;
50 std::size_t blockAlignment_;
52
53 virtual void* allocateImp(std::size_t bytes, std::size_t alignment) override {
54 if (blockSize_ < bytes || blockAlignment_ < alignment || !head_) {
55 throw std::bad_alloc();
56 }
57
58 void* allocatedBlock = head_ + 1;
59 head_ = head_->next;
60 return allocatedBlock;
61 }
62
63 virtual void deallocateImp(
64 void* address,
65 [[maybe_unused]] std::size_t bytes,
66 [[maybe_unused]] std::size_t alignment) override {
67 Header* header = reinterpret_cast<Header*>(address) - 1;
68 header->next = head_;
69 head_ = header;
70 }
71 };
72}
A memory resource holder interface for the PolymorphicAllocator. Responsible for allocate and dealloc...
PoolMemoryResource(void *buffer, std::size_t capacity, std::size_t blockSize, std::size_t blockAlignment=sizeof(std::max_align_t))
virtual void * allocateImp(std::size_t bytes, std::size_t alignment) override
virtual void deallocateImp(void *address, std::size_t bytes, std::size_t alignment) override
Header * alignWithHeader(std::size_t alignment, std::size_t size, void *&buffer, std::size_t &capacity) noexcept
Align the header + buffer to their corresponding alignments. If the capacity is not big enough,...