|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include <memory_resource> |
| 4 | +#include <utility> |
| 5 | +#include "esp_heap_caps.h" |
| 6 | + |
| 7 | +namespace idf::memory { |
| 8 | + |
| 9 | +/** |
| 10 | + * Memory capabilities for memory allocation |
| 11 | + * |
| 12 | + * Refer to IDF documentation on memory allocation for the usage of each of them. |
| 13 | + */ |
| 14 | +enum class capabilities : uint32_t { |
| 15 | + not_specified = MALLOC_CAP_DEFAULT, |
| 16 | + adressable_8bit = MALLOC_CAP_8BIT, |
| 17 | + adressable_32bit = MALLOC_CAP_32BIT, |
| 18 | + dma = MALLOC_CAP_DMA, |
| 19 | + executable = MALLOC_CAP_EXEC, |
| 20 | + from_spiram = MALLOC_CAP_SPIRAM, |
| 21 | + internal = MALLOC_CAP_INTERNAL, |
| 22 | + retention_dma = MALLOC_CAP_RETENTION, |
| 23 | + rtc = MALLOC_CAP_RTCRAM |
| 24 | +}; |
| 25 | + |
| 26 | +constexpr capabilities operator|(const capabilities lhs, const capabilities rhs) |
| 27 | +{ |
| 28 | + return capabilities{std::to_underlying(lhs) | std::to_underlying(rhs)}; |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | +* @brief Memory resource to be used with polymorphic allocators |
| 33 | +*/ |
| 34 | +class resource : public std::pmr::memory_resource { |
| 35 | +public: |
| 36 | + static constexpr auto tag = "esp_memory_resource"; |
| 37 | + /** |
| 38 | + * Construct a resource with the selected capabilities and upstream resource. |
| 39 | + * |
| 40 | + * @param cap capabilities to use in this allocator. Refer to idf memory allocation documentation to understand the effects. Default: capabilities::not_specified |
| 41 | + * @param upstream memory resource to use when allocation fails. It can be used to compose memory resources. Default: default resource. |
| 42 | + */ |
| 43 | + explicit resource(capabilities cap=capabilities::not_specified, std::pmr::memory_resource * upstream = std::pmr::get_default_resource()) : cap(cap), upstream(upstream) {} |
| 44 | + |
| 45 | +private: |
| 46 | + void * do_allocate(size_t bytes, [[maybe_unused]] size_t alignment) override; |
| 47 | + void do_deallocate(void *ptr, size_t bytes, size_t alignment) override; |
| 48 | + [[nodiscard]] bool do_is_equal(const memory_resource &other) const noexcept override; |
| 49 | + capabilities cap; |
| 50 | + std::pmr::memory_resource * upstream; |
| 51 | +}; |
| 52 | + |
| 53 | + |
| 54 | +} |
0 commit comments