From 16d5d29049c08e21f57f7928ceedf40586a2d294 Mon Sep 17 00:00:00 2001 From: jacqueline Date: Sat, 3 Dec 2022 11:10:06 +1100 Subject: Use std::span (backported) and std::byte to make our buffers safer --- lib/psram_allocator/CMakeLists.txt | 1 + lib/psram_allocator/include/psram_allocator.h | 79 +++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 lib/psram_allocator/CMakeLists.txt create mode 100644 lib/psram_allocator/include/psram_allocator.h (limited to 'lib') diff --git a/lib/psram_allocator/CMakeLists.txt b/lib/psram_allocator/CMakeLists.txt new file mode 100644 index 00000000..67111692 --- /dev/null +++ b/lib/psram_allocator/CMakeLists.txt @@ -0,0 +1 @@ +idf_component_register(INCLUDE_DIRS "include") diff --git a/lib/psram_allocator/include/psram_allocator.h b/lib/psram_allocator/include/psram_allocator.h new file mode 100644 index 00000000..1649f8bd --- /dev/null +++ b/lib/psram_allocator/include/psram_allocator.h @@ -0,0 +1,79 @@ +/// \copyright +/// Copyright 2021 Mike Dunston (https://github.com/atanisoft) +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// +/// \file psram_allocator.h +/// This file declares an allocator that provides memory from PSRAM rather than +/// internal memory. + +#pragma once + +#include +#include "sdkconfig.h" + +template +class PSRAMAllocator +{ +public: + using value_type = T; + + PSRAMAllocator() noexcept + { + } + + template constexpr PSRAMAllocator(const PSRAMAllocator&) noexcept + { + } + + [[nodiscard]] value_type* allocate(std::size_t n) + { +#if CONFIG_SPIRAM + // attempt to allocate in PSRAM first + auto p = + static_cast( + heap_caps_malloc(n * sizeof(value_type), MALLOC_CAP_SPIRAM)); + if (p) + { + return p; + } +#endif // CONFIG_SPIRAM + + // If the allocation in PSRAM failed (or PSRAM not enabled), try to + // allocate from the default memory pool. + auto p2 = + static_cast( + heap_caps_malloc(n * sizeof(value_type), MALLOC_CAP_DEFAULT)); + if (p2) + { + return p2; + } + + throw std::bad_alloc(); + } + + void deallocate(value_type* p, std::size_t) noexcept + { + heap_caps_free(p); + } +}; +template +bool operator==(const PSRAMAllocator&, const PSRAMAllocator&) +{ + return true; +} +template +bool operator!=(const PSRAMAllocator& x, const PSRAMAllocator& y) +{ + return !(x == y); +} -- cgit v1.2.3