Skip to content

Instantly share code, notes, and snippets.

@newlawrence
Created November 20, 2018 19:22
Show Gist options
  • Save newlawrence/3996ed6a2dae8495334fb0ef0f9bac18 to your computer and use it in GitHub Desktop.
Save newlawrence/3996ed6a2dae8495334fb0ef0f9bac18 to your computer and use it in GitHub Desktop.
Contiguous memory resource
#include <memory_resource>
template<typename T>
class contiguous_memory_resource : public std::pmr::memory_resource {
std::pmr::memory_resource* _upstream;
std::size_t _size;
void* _buffer;
void* _offset;
void* do_allocate(size_t bytes, size_t alignment) override {
std::uintptr_t buffer = reinterpret_cast<std::uintptr_t>(_buffer);
std::uintptr_t offset = reinterpret_cast<std::uintptr_t>(_offset);
std::size_t blocks = bytes / sizeof(T) + (bytes % sizeof(T) ? 1 : 0);
void* ptr = _offset;
offset = (offset / alignof(T) + blocks) * alignof(T);
if (alignment != alignof(T) || offset - buffer > _size)
throw std::bad_alloc{};
_offset = reinterpret_cast<void*>(offset);
return ptr;
}
void do_deallocate(void* buffer, size_t bytes, size_t alignment) override {}
bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override {
return this == &other;
}
public:
contiguous_memory_resource(
std::size_t size,
std::pmr::memory_resource* upstream=std::pmr::get_default_resource()
) :
_upstream{upstream},
_size{size},
_buffer{_upstream->allocate(_size, alignof(T))},
_offset{_buffer}
{}
~contiguous_memory_resource() {
_upstream->deallocate(_buffer, _size, alignof(T));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment