1 | // Copyright (C) 2021 The Qt Company Ltd. |
---|---|
2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only |
3 | |
4 | #include "glslmemorypool_p.h" |
5 | #include <cstring> |
6 | #include <cassert> |
7 | #include <cstdlib> |
8 | |
9 | QT_BEGIN_NAMESPACE |
10 | |
11 | using namespace GLSL; |
12 | |
13 | MemoryPool::MemoryPool() |
14 | : _blocks(nullptr), |
15 | _allocatedBlocks(0), |
16 | _blockCount(-1), |
17 | _ptr(nullptr), |
18 | _end(nullptr) |
19 | { } |
20 | |
21 | MemoryPool::~MemoryPool() |
22 | { |
23 | if (_blocks) { |
24 | for (int i = 0; i < _allocatedBlocks; ++i) { |
25 | if (char *b = _blocks[i]) |
26 | std::free(ptr: b); |
27 | } |
28 | |
29 | std::free(ptr: _blocks); |
30 | } |
31 | } |
32 | |
33 | void MemoryPool::reset() |
34 | { |
35 | _blockCount = -1; |
36 | _ptr = _end = nullptr; |
37 | } |
38 | |
39 | void *MemoryPool::allocate_helper(size_t size) |
40 | { |
41 | assert(size < BLOCK_SIZE); |
42 | |
43 | if (++_blockCount == _allocatedBlocks) { |
44 | if (! _allocatedBlocks) |
45 | _allocatedBlocks = DEFAULT_BLOCK_COUNT; |
46 | else |
47 | _allocatedBlocks *= 2; |
48 | |
49 | _blocks = (char **) realloc(ptr: _blocks, size: sizeof(char *) * _allocatedBlocks); |
50 | |
51 | for (int index = _blockCount; index < _allocatedBlocks; ++index) |
52 | _blocks[index] = nullptr; |
53 | } |
54 | |
55 | char *&block = _blocks[_blockCount]; |
56 | |
57 | if (! block) |
58 | block = (char *) std::malloc(size: BLOCK_SIZE); |
59 | |
60 | _ptr = block; |
61 | _end = _ptr + BLOCK_SIZE; |
62 | |
63 | void *addr = _ptr; |
64 | _ptr += size; |
65 | return addr; |
66 | } |
67 | |
68 | Managed::Managed() |
69 | { } |
70 | |
71 | Managed::~Managed() |
72 | { } |
73 | |
74 | void *Managed::operator new(size_t size, MemoryPool *pool) |
75 | { return pool->allocate(size); } |
76 | |
77 | void Managed::operator delete(void *) |
78 | { } |
79 | |
80 | void Managed::operator delete(void *, MemoryPool *) |
81 | { } |
82 | |
83 | QT_END_NAMESPACE |
84 |