Skip to content

Commit

Permalink
AlignUp, AlignDown helpers (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
walbourn authored Feb 16, 2018
1 parent 151c20b commit f733b9c
Showing 2 changed files with 27 additions and 16 deletions.
25 changes: 25 additions & 0 deletions Inc/DirectXHelpers.h
Original file line number Diff line number Diff line change
@@ -173,4 +173,29 @@ namespace DirectX

commandList->ResourceBarrier(1, &desc);
}

// Helpers for aligning values by a power of 2
template<typename T>
inline T AlignDown(T size, size_t alignment)
{
if (alignment > 0)
{
assert(((alignment - 1) & alignment) == 0);
T mask = static_cast<T>(alignment - 1);
return size & ~mask;
}
return size;
}

template<typename T>
inline T AlignUp(T size, size_t alignment)
{
if (alignment > 0)
{
assert(((alignment - 1) & alignment) == 0);
T mask = static_cast<T>(alignment - 1);
return (size + mask) & ~mask;
}
return size;
}
}
18 changes: 2 additions & 16 deletions Src/LinearAllocator.cpp
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit f733b9c

Please sign in to comment.