| 1 | // Copyright (C) 2025 The Qt Company Ltd. |
| 2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
| 3 | |
| 4 | #include "qmemory_resource_tlsf_p.h" |
| 5 | |
| 6 | #include <QtCore/qassert.h> |
| 7 | |
| 8 | #include <memory_resource> |
| 9 | |
| 10 | #include <tlsf.h> |
| 11 | |
| 12 | QT_BEGIN_NAMESPACE |
| 13 | |
| 14 | namespace QtMultimediaPrivate { |
| 15 | |
| 16 | QTlsfMemoryResource::QTlsfMemoryResource(std::size_t preallocatedBytes, memory_resource *upstream): |
| 17 | m_allocationSize { |
| 18 | preallocatedBytes + 8192, // over-allocate by 8k for tlsf header |
| 19 | }, |
| 20 | m_upstream{ |
| 21 | upstream, |
| 22 | } |
| 23 | { |
| 24 | m_buffer = reinterpret_cast<std::byte *>(operator new(m_allocationSize, poolAlignment)); |
| 25 | |
| 26 | m_tlsf = QtPrivate::tlsf_create_with_pool(mem: m_buffer, bytes: m_allocationSize); |
| 27 | Q_ASSERT(m_tlsf); |
| 28 | } |
| 29 | |
| 30 | QTlsfMemoryResource::~QTlsfMemoryResource() |
| 31 | { |
| 32 | QtPrivate::tlsf_destroy(tlsf: m_tlsf); |
| 33 | ::operator delete(m_buffer, poolAlignment); |
| 34 | } |
| 35 | |
| 36 | void *QTlsfMemoryResource::do_allocate(size_t bytes, size_t alignment) |
| 37 | { |
| 38 | void *ret = QtPrivate::tlsf_memalign(tlsf: m_tlsf, align: alignment, bytes); |
| 39 | if (Q_UNLIKELY(ret == nullptr)) |
| 40 | ret = m_upstream->allocate(bytes: bytes, alignment: alignment); |
| 41 | |
| 42 | return ret; |
| 43 | } |
| 44 | |
| 45 | void QTlsfMemoryResource::do_deallocate(void *p, size_t bytes, size_t alignment) |
| 46 | { |
| 47 | if (Q_LIKELY(p >= m_buffer && p < m_buffer + m_allocationSize)) |
| 48 | QtPrivate::tlsf_free(tlsf: m_tlsf, ptr: p); |
| 49 | else |
| 50 | m_upstream->deallocate(p: p, bytes: bytes, alignment: alignment); |
| 51 | } |
| 52 | |
| 53 | bool QTlsfMemoryResource::do_is_equal(const memory_resource &other) const noexcept |
| 54 | { |
| 55 | return this == &other; |
| 56 | } |
| 57 | |
| 58 | } // namespace QtMultimediaPrivate |
| 59 | |
| 60 | QT_END_NAMESPACE |
| 61 | |