scopedallocator.cpp (1347B)
1 // This file is part of Blend2D project <https://blend2d.com> 2 // 3 // See blend2d.h or LICENSE.md for license and copyright information 4 // SPDX-License-Identifier: Zlib 5 6 #include "../api-build_p.h" 7 #include "../support/intops_p.h" 8 #include "../support/scopedallocator_p.h" 9 10 namespace bl { 11 12 // bl::ScopedAllocator - Alloc 13 // =========================== 14 15 void* ScopedAllocator::alloc(size_t size, size_t alignment) noexcept { 16 // First try to allocate from the local memory pool. 17 uint8_t* p = IntOps::align_up(pool_ptr, alignment); 18 size_t remain = size_t(IntOps::usub_saturate((uintptr_t)pool_end, (uintptr_t)p)); 19 20 if (remain >= size) { 21 pool_ptr = p + size; 22 return p; 23 } 24 25 // Bail to malloc if local pool was either not provided or didn't have the required capacity. 26 size_t size_with_overhead = size + sizeof(Link) + (alignment - 1); 27 p = static_cast<uint8_t*>(malloc(size_with_overhead)); 28 29 if (p == nullptr) 30 return nullptr; 31 32 reinterpret_cast<Link*>(p)->next = links; 33 links = reinterpret_cast<Link*>(p); 34 35 return IntOps::align_up(p + sizeof(Link), alignment); 36 } 37 38 // ScopedAllocator - Reset 39 // ======================= 40 41 void ScopedAllocator::reset() noexcept { 42 Link* link = links; 43 while (link) { 44 Link* next = link->next; 45 free(link); 46 link = next; 47 } 48 49 links = nullptr; 50 pool_ptr = pool_mem; 51 } 52 53 } // {bl}