File: fallback_allocator.cpp

package info (click to toggle)
foonathan-memory 0.7-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,748 kB
  • sloc: cpp: 12,014; xml: 139; sh: 49; makefile: 22
file content (59 lines) | stat: -rw-r--r-- 1,883 bytes parent folder | download
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
59
// Copyright (C) 2015-2020 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.

#include <foonathan/memory/fallback_allocator.hpp>

#include <catch.hpp>

#include <foonathan/memory/allocator_storage.hpp>
#include "test_allocator.hpp"

using namespace foonathan::memory;

TEST_CASE("fallback_allocator", "[adapter]")
{
    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);
}