1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
// Copyright (C) 2015-2025 Jonathan Müller and foonathan/memory contributors
// SPDX-License-Identifier: Zlib
#include <foonathan/memory/fallback_allocator.hpp>
#include <doctest/doctest.h>
#include <foonathan/memory/allocator_storage.hpp>
#include "test_allocator.hpp"
using namespace foonathan::memory;
TEST_CASE("fallback_allocator")
{
struct test_compositioning : test_allocator
{
bool fail = false;
void* try_allocate_node(std::size_t size, std::size_t alignment)
{
return fail ? nullptr : allocate_node(size, alignment);
}
bool try_deallocate_node(void* ptr, std::size_t size, std::size_t alignment)
{
if (fail)
return false;
deallocate_node(ptr, size, alignment);
return true;
}
} default_alloc;
test_allocator fallback_alloc;
using allocator = fallback_allocator<allocator_reference<test_compositioning>,
allocator_reference<test_allocator>>;
allocator alloc(default_alloc, fallback_alloc);
REQUIRE(default_alloc.no_allocated() == 0u);
REQUIRE(fallback_alloc.no_allocated() == 0u);
auto ptr = alloc.allocate_node(1, 1);
REQUIRE(default_alloc.no_allocated() == 1u);
REQUIRE(fallback_alloc.no_allocated() == 0u);
alloc.deallocate_node(ptr, 1, 1);
REQUIRE(default_alloc.no_deallocated() == 1u);
REQUIRE(fallback_alloc.no_deallocated() == 0u);
default_alloc.fail = true;
ptr = alloc.allocate_node(1, 1);
REQUIRE(default_alloc.no_allocated() == 0u);
REQUIRE(fallback_alloc.no_allocated() == 1u);
alloc.deallocate_node(ptr, 1, 1);
REQUIRE(default_alloc.no_deallocated() == 1u);
REQUIRE(fallback_alloc.no_deallocated() == 1u);
}
|