From eaed109fe9b27097f62831f897a1606d8c84ab7c Mon Sep 17 00:00:00 2001 From: apio Date: Tue, 7 Mar 2023 20:37:30 +0100 Subject: [PATCH] libluna: Let Alignment.h functions take non-powers-of-two Since the alignment must be known at compile-time, the compiler will optimize for powers of two and leave an inefficient implementation for other values. --- libluna/include/luna/Alignment.h | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/libluna/include/luna/Alignment.h b/libluna/include/luna/Alignment.h index 68b17e4a..2a34f1f3 100644 --- a/libluna/include/luna/Alignment.h +++ b/libluna/include/luna/Alignment.h @@ -2,10 +2,8 @@ #include #include -// Must ALWAYS be called with a power of two as alignment. -template constexpr T is_aligned(T value) +template constexpr inline T is_aligned(T value) { - static_assert(IsPowerOfTwo); return (value % alignment == 0); } @@ -13,10 +11,8 @@ static_assert(is_aligned<512>(1024u)); static_assert(!is_aligned<32>(235u)); static_assert(is_aligned<4096>(40960u)); -// Must ALWAYS be called with a power of two as alignment. -template constexpr T align_down(T value) +template constexpr inline T align_down(T value) { - static_assert(IsPowerOfTwo); return value - value % alignment; } @@ -24,8 +20,7 @@ static_assert(align_down<512>(598ul) == 512ul); static_assert(align_down<64>(194ul) == 192ul); static_assert(align_down<32>(64ul) == 64ul); -// Must ALWAYS be called with a power of two as alignment. -template constexpr T align_up(T value) +template constexpr inline T align_up(T value) { if (is_aligned(value)) return value; return align_down(value) + alignment; @@ -47,7 +42,7 @@ static_assert(get_blocks_from_size(0, 256) == 0); // Offset a pointer by exactly bytes, no matter the type. Useful to avoid the quirks that come from C pointer // arithmetic. -template constexpr T* offset_ptr(T* ptr, Offset offset) +template constexpr inline T* offset_ptr(T* ptr, Offset offset) { return (T*)((u8*)ptr + offset); }