From f733b9cc15452116b40500eb89b00f5c63fd9dfd Mon Sep 17 00:00:00 2001 From: Chuck Walbourn Date: Thu, 15 Feb 2018 18:05:02 -0800 Subject: [PATCH] AlignUp, AlignDown helpers (#29) --- Inc/DirectXHelpers.h | 25 +++++++++++++++++++++++++ Src/LinearAllocator.cpp | 18 ++---------------- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/Inc/DirectXHelpers.h b/Inc/DirectXHelpers.h index 4080b056..57447ac4 100644 --- a/Inc/DirectXHelpers.h +++ b/Inc/DirectXHelpers.h @@ -173,4 +173,29 @@ namespace DirectX commandList->ResourceBarrier(1, &desc); } + + // Helpers for aligning values by a power of 2 + template + inline T AlignDown(T size, size_t alignment) + { + if (alignment > 0) + { + assert(((alignment - 1) & alignment) == 0); + T mask = static_cast(alignment - 1); + return size & ~mask; + } + return size; + } + + template + inline T AlignUp(T size, size_t alignment) + { + if (alignment > 0) + { + assert(((alignment - 1) & alignment) == 0); + T mask = static_cast(alignment - 1); + return (size + mask) & ~mask; + } + return size; + } } \ No newline at end of file diff --git a/Src/LinearAllocator.cpp b/Src/LinearAllocator.cpp index 49be2c0e..660db71e 100644 --- a/Src/LinearAllocator.cpp +++ b/Src/LinearAllocator.cpp @@ -25,20 +25,6 @@ using namespace DirectX; using Microsoft::WRL::ComPtr; -namespace -{ - inline size_t AlignOffset(size_t offset, size_t alignment) - { - if (alignment > 0) - { - // Alignment must be a power of 2 - assert((alignment & (alignment - 1)) == 0); - offset = (offset + alignment - 1) & ~(alignment - 1); - } - return offset; - } -} - LinearAllocatorPage::LinearAllocatorPage() : pPrevPage(nullptr) , pNextPage(nullptr) @@ -53,7 +39,7 @@ LinearAllocatorPage::LinearAllocatorPage() size_t LinearAllocatorPage::Suballocate(_In_ size_t size, _In_ size_t alignment) { - size_t offset = AlignOffset(mOffset, alignment); + size_t offset = AlignUp(mOffset, alignment); #ifdef _DEBUG if (offset + size > mSize) throw std::exception("Out of free memory in page suballoc"); @@ -278,7 +264,7 @@ LinearAllocatorPage* LinearAllocator::FindPageForAlloc( { for (LinearAllocatorPage* page = list; page != nullptr; page = page->pNextPage) { - size_t offset = AlignOffset(page->mOffset, alignment); + size_t offset = AlignUp(page->mOffset, alignment); if (offset + sizeBytes <= m_increment) return page; }