aboutsummaryrefslogtreecommitdiff
path: root/experimental/lfpAlloc/PoolDispatcher.hpp
blob: e4d1427f33709ca5eba148fe9de5e2c8a80b1926 (plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#ifndef LF_POOL_DISPATCHER
#define LF_POOL_DISPATCHER

#include <tuple>
#include <cassert>
#include <cstddef>
#include <lfpAlloc/Pool.hpp>

#ifndef LFP_ALLOCATIONS_PER_CHUNK
#define LFP_ALLOCATIONS_PER_CHUNK 64 * 100
#endif

namespace lfpAlloc {
namespace detail {

template <std::size_t Num, uint16_t... Ts>
struct Pools : Pools<Num - 1, alignof(std::max_align_t) * Num, Ts...> {};

template <uint16_t... Size>
struct Pools<0, Size...> {
    using type = std::tuple<Pool<Size, LFP_ALLOCATIONS_PER_CHUNK>...>;
};
}

template <std::size_t NumPools>
class PoolDispatcher {
public:
    void* allocate(std::size_t size) { return dispatchAllocate<0>(size); }

    void deallocate(void* p, std::size_t size) noexcept {
        dispatchDeallocate<0>(p, size);
    }

private:
    thread_local static typename detail::Pools<NumPools>::type pools_;
    static_assert(NumPools > 0, "Invalid number of pools");

    template <std::size_t Index>
        typename std::enable_if <
        Index<NumPools, void*>::type
        dispatchAllocate(std::size_t const& requestSize) {
        if (requestSize <= std::get<Index>(pools_).CellSize) {
            return std::get<Index>(pools_).allocate();
        } else {
            return dispatchAllocate<Index + 1>(requestSize);
        }
    }

    template <std::size_t Index>
    typename std::enable_if<!(Index < NumPools), void*>::type
    dispatchAllocate(std::size_t const&) {
        assert(false && "Invalid allocation size.");
        return nullptr;
    }

    template <std::size_t Index>
        typename std::enable_if <
        Index<NumPools>::type
        dispatchDeallocate(void* p, std::size_t const& requestSize) noexcept {
        if (requestSize <= std::get<Index>(pools_).CellSize) {
            std::get<Index>(pools_).deallocate(p);
        } else {
            dispatchDeallocate<Index + 1>(p, requestSize);
        }
    }

    template <std::size_t Index>
    typename std::enable_if<!(Index < NumPools)>::type
    dispatchDeallocate(void*, std::size_t const&) noexcept {
        assert(false && "Invalid deallocation size.");
    }
};

template <std::size_t NumPools>
thread_local typename detail::Pools<NumPools>::type
    PoolDispatcher<NumPools>::pools_;
}

#endif