#include #include #include #include "freertos/free_rtos_allocator.hpp" extern "C" void * pvPortMalloc( size_t bytes ) { return bytes <= 128U ? std::malloc( bytes ) : nullptr; } extern "C" void vPortFree( void * memory ) { std::free( memory ); } static_assert( sizeof( freertos::MemoryResource ) == 3U * sizeof( void * ) ); static_assert( !std::is_polymorphic< freertos::MemoryResource >::value ); static_assert( !std::is_polymorphic< freertos::HeapResource >::value ); static_assert( !std::is_polymorphic< freertos::StaticArenaResource >::value ); int main() { freertos::HeapResource heap; const freertos::FreeRtosAllocator< uint32_t > heap_allocator { heap.resource() }; uint32_t * const heap_values = heap_allocator.try_allocate( 8U ); assert( heap_values != nullptr ); assert( reinterpret_cast< uintptr_t >( heap_values ) % alignof( uint32_t ) == 0U ); heap_values[ 0 ] = 42U; assert( heap_values[ 0 ] == 42U ); const size_t failed_before_overflow = heap.failed_allocations(); const size_t overflow = SIZE_MAX / sizeof( uint32_t ) + 1U; assert( decltype( heap_allocator )::count_overflows( overflow ) ); assert( heap_allocator.try_allocate( overflow ) == nullptr ); assert( heap.failed_allocations() == failed_before_overflow ); assert( heap_allocator.try_allocate( 64U ) == nullptr ); assert( heap.failed_allocations() == failed_before_overflow + 1U ); heap_allocator.deallocate( heap_values, 8U ); assert( heap.successful_allocations() == 1U ); assert( heap.deallocations() == 1U ); alignas( 8 ) uint8_t storage[ 64 ] {}; freertos::StaticArenaResource arena { storage, sizeof( storage ), 8U }; const freertos::MemoryResource arena_view = arena.resource(); void * const byte = arena_view.allocate_bytes( 1U, 1U ); void * const aligned = arena_view.allocate_bytes( 4U, 4U ); assert( byte == &storage[ 0 ] ); assert( reinterpret_cast< uintptr_t >( aligned ) % 4U == 0U ); assert( arena.used() == 8U ); assert( arena.owns( aligned ) ); const size_t used_before_failure = arena.used(); assert( arena_view.allocate_bytes( 64U, 4U ) == nullptr ); assert( arena.used() == used_before_failure ); arena_view.deallocate_bytes( aligned, 4U, 4U ); assert( arena.used() == used_before_failure ); arena.reset(); assert( arena.used() == 0U ); assert( arena.remaining() == sizeof( storage ) ); return 0; }