summaryrefslogtreecommitdiffstats
path: root/Common/interface/FixedLinearAllocator.hpp
blob: 327ed8adcfc977de43fc61be6ba15037481a009f (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*
 *  Copyright 2019-2021 Diligent Graphics LLC
 *  Copyright 2015-2019 Egor Yusov
 *  
 *  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.
 *
 *  In no event and under no legal theory, whether in tort (including negligence), 
 *  contract, or otherwise, unless required by applicable law (such as deliberate 
 *  and grossly negligent acts) or agreed to in writing, shall any Contributor be
 *  liable for any damages, including any direct, indirect, special, incidental, 
 *  or consequential damages of any character arising as a result of this License or 
 *  out of the use or inability to use the software (including but not limited to damages 
 *  for loss of goodwill, work stoppage, computer failure or malfunction, or any and 
 *  all other commercial damages or losses), even if such Contributor has been advised 
 *  of the possibility of such damages.
 */

#pragma once

/// \file
/// Defines Diligent::FixedLinearAllocator class

#include <vector>

#include "../../Primitives/interface/BasicTypes.h"
#include "../../Primitives/interface/MemoryAllocator.h"
#include "../../Platforms/Basic/interface/DebugUtilities.hpp"
#include "CompilerDefinitions.h"
#include "Align.hpp"

namespace Diligent
{

/// Implementation of a linear allocator on a fixed-size memory page
class FixedLinearAllocator
{
public:
    // clang-format off
    FixedLinearAllocator           (const FixedLinearAllocator&) = delete;
    FixedLinearAllocator& operator=(const FixedLinearAllocator&) = delete;
    FixedLinearAllocator& operator=(FixedLinearAllocator&&)      = delete;
    // clang-format on

    explicit FixedLinearAllocator(IMemoryAllocator& Allocator) noexcept :
        m_pAllocator{&Allocator}
    {}

    FixedLinearAllocator(FixedLinearAllocator&& Other) noexcept :
        // clang-format off
        m_pDataStart   {Other.m_pDataStart   },
        m_pCurrPtr     {Other.m_pCurrPtr     },
        m_ReservedSize {Other.m_ReservedSize },
        m_CurrAlignment{Other.m_CurrAlignment},
        m_pAllocator   {Other.m_pAllocator   }
#if DILIGENT_DEBUG
        , m_DbgCurrAllocation{Other.m_DbgCurrAllocation}
        , m_DbgAllocations{std::move(Other.m_DbgAllocations)}
#endif
    // clang-format on
    {
        Other.Reset();
    }

    ~FixedLinearAllocator()
    {
        Free();
    }

    void Free()
    {
        if (m_pDataStart != nullptr && m_pAllocator != nullptr)
        {
            m_pAllocator->Free(m_pDataStart);
        }
        Reset();
    }

    NODISCARD void* Release()
    {
        void* Ptr = m_pDataStart;
        Reset();
        return Ptr;
    }

    NODISCARD void* ReleaseOwnership() noexcept
    {
        m_pAllocator = nullptr;
        return GetDataPtr();
    }

    NODISCARD void* GetDataPtr() const noexcept
    {
        return m_pDataStart;
    }

    void AddSpace(size_t size, size_t alignment) noexcept
    {
        VERIFY(m_pDataStart == nullptr, "Memory has already been allocated");
        VERIFY(IsPowerOfTwo(alignment), "Alignment is not a power of two!");

        if (size == 0)
            return;

        if (m_CurrAlignment == 0)
        {
            VERIFY(m_ReservedSize == 0, "This is expected to be a very first time the space is added");
            m_CurrAlignment = sizeof(void*);
        }

        if (alignment > m_CurrAlignment)
        {
            // Reserve extra space that may be needed for alignment
            m_ReservedSize += alignment - m_CurrAlignment;
        }
        m_CurrAlignment = alignment;

        size = AlignUp(size, alignment);
        m_ReservedSize += size;

#if DILIGENT_DEBUG
        m_DbgAllocations.emplace_back(size, alignment, m_ReservedSize);
#endif
    }

    template <typename T>
    void AddSpace(size_t count = 1) noexcept
    {
        AddSpace(sizeof(T) * count, alignof(T));
    }

    void AddSpaceForString(const Char* str) noexcept
    {
        if (str != nullptr)
            AddSpace<Char>(strlen(str) + 1);
    }

    void AddSpaceForString(const String& str) noexcept
    {
        if (!str.empty())
            AddSpace<String::value_type>(str.length() + 1);
    }

    void Reserve(size_t size)
    {
        VERIFY(m_pDataStart == nullptr, "Memory has already been allocated");
        VERIFY(m_ReservedSize == 0, "Space has been added to the allocator and will be overriden");
        m_ReservedSize = size;
        Reserve();
    }

    void Reserve()
    {
        VERIFY(m_pDataStart == nullptr, "Memory has already been allocated");
        VERIFY(m_pAllocator != nullptr, "Allocator must not be null");
        // Make sure the data size is at least sizeof(void*)-aligned
        m_ReservedSize = AlignUp(m_ReservedSize, sizeof(void*));
        if (m_ReservedSize > 0)
        {
            m_pDataStart = reinterpret_cast<uint8_t*>(m_pAllocator->Allocate(m_ReservedSize, "Raw memory for linear allocator", __FILE__, __LINE__));
            VERIFY(m_pDataStart == AlignUp(m_pDataStart, sizeof(void*)), "Memory pointer must be at least sizeof(void*)-aligned");

            m_pCurrPtr = m_pDataStart;
        }
        m_CurrAlignment = sizeof(void*);
    }

    NODISCARD void* Allocate(size_t size, size_t alignment)
    {
        VERIFY(size == 0 || m_pDataStart != nullptr, "Memory has not been allocated");
        VERIFY(IsPowerOfTwo(alignment), "Alignment is not a power of two!");

        if (size == 0)
            return nullptr;

        size = AlignUp(size, alignment);

#if DILIGENT_DEBUG
        VERIFY(m_DbgCurrAllocation < m_DbgAllocations.size(), "Allocation number exceed the number of allocations that were originally reserved.");
        const auto& CurrAllocation = m_DbgAllocations[m_DbgCurrAllocation++];
        VERIFY(CurrAllocation.size == size, "Allocation size (", size, ") does not match the initially requested size (", CurrAllocation.size, ")");
        VERIFY(CurrAllocation.alignment == alignment, "Allocation alignment (", alignment, ") does not match the initially requested alignment (", CurrAllocation.alignment, ")");
#endif

        VERIFY(AlignUp(m_pCurrPtr, m_CurrAlignment) == m_pCurrPtr, "Current pointer is not aligned as expected");
        m_pCurrPtr      = AlignUp(m_pCurrPtr, alignment);
        m_CurrAlignment = alignment;

        VERIFY(m_pCurrPtr + size <= m_pDataStart + CurrAllocation.reserved_size,
               "Allocation size exceeds the initially reserved space. This is likely a bug.");

        auto* ptr = m_pCurrPtr;
        m_pCurrPtr += size;

        VERIFY(m_pCurrPtr <= m_pDataStart + m_ReservedSize, "Allocation size exceeds the reserved space");

        return ptr;
    }

    template <typename T>
    NODISCARD T* Allocate(size_t count = 1)
    {
        return reinterpret_cast<T*>(Allocate(sizeof(T) * count, alignof(T)));
    }

    template <typename T, typename... Args>
    NODISCARD T* Construct(Args&&... args)
    {
        T* Ptr = Allocate<T>();
        new (Ptr) T{std::forward<Args>(args)...};
        return Ptr;
    }

    template <typename T, typename... Args>
    NODISCARD T* ConstructArray(size_t count, const Args&... args)
    {
        T* Ptr = Allocate<T>(count);
        for (size_t i = 0; i < count; ++i)
        {
            new (Ptr + i) T{args...};
        }
        return Ptr;
    }

    template <typename T>
    NODISCARD T* Copy(const T& Src)
    {
        return Construct<T>(Src);
    }

    template <typename T>
    NODISCARD T* CopyArray(const T* Src, size_t count)
    {
        T* Dst = Allocate<T>(count);
        for (size_t i = 0; i < count; ++i)
        {
            new (Dst + i) T{Src[i]};
        }
        return Dst;
    }

    NODISCARD Char* CopyString(const char* Str)
    {
        if (Str == nullptr)
            return nullptr;

        auto* Ptr = reinterpret_cast<Char*>(Allocate(strlen(Str) + 1, 1));
        Char* Dst = Ptr;

        const auto* pDataEnd = reinterpret_cast<Char*>(m_pDataStart) + m_ReservedSize;
        while (*Str != 0 && Dst < pDataEnd)
        {
            *(Dst++) = *(Str++);
        }
        if (Dst < pDataEnd)
            *(Dst++) = 0;
        else
            UNEXPECTED("Not enough space reserved for the string");

        VERIFY_EXPR(reinterpret_cast<Char*>(m_pCurrPtr) == Dst);
        return Ptr;
    }

    NODISCARD Char* CopyString(const std::string& Str)
    {
        return CopyString(Str.c_str());
    }

    NODISCARD size_t GetCurrentSize() const
    {
        VERIFY(m_pDataStart != nullptr, "Memory has not been allocated");
        return static_cast<size_t>(m_pCurrPtr - m_pDataStart);
    }

    NODISCARD size_t GetReservedSize() const
    {
        return m_ReservedSize;
    }

private:
    void Reset()
    {
        m_pDataStart    = nullptr;
        m_pCurrPtr      = nullptr;
        m_ReservedSize  = 0;
        m_CurrAlignment = 0;
        m_pAllocator    = nullptr;

#if DILIGENT_DEBUG
        m_DbgCurrAllocation = 0;
        m_DbgAllocations.clear();
#endif
    }

    uint8_t*          m_pDataStart    = nullptr;
    uint8_t*          m_pCurrPtr      = nullptr;
    size_t            m_ReservedSize  = 0;
    size_t            m_CurrAlignment = 0;
    IMemoryAllocator* m_pAllocator    = nullptr;

#if DILIGENT_DEBUG
    size_t m_DbgCurrAllocation = 0;
    struct DbgAllocationInfo
    {
        const size_t size;
        const size_t alignment;
        const size_t reserved_size;

        DbgAllocationInfo(size_t _size, size_t _alignment, size_t _reserved_size) :
            size{_size},
            alignment{_alignment},
            reserved_size{_reserved_size}
        {
        }
    };
    std::vector<DbgAllocationInfo> m_DbgAllocations;
#endif
};

} // namespace Diligent