Adding isAligned impl for numeric types

Supports numeric types (e.g. size_t)
Supports constexpr evaluation

Change-Id: I6942bdaa12c39df95dcdee84e5d5851c9ec89be8
This commit is contained in:
Chodor, Jaroslaw 2018-01-08 02:07:12 +01:00
parent 9ca3e8b1ab
commit f6eb2617b9
2 changed files with 22 additions and 3 deletions

View File

@ -93,9 +93,13 @@ inline size_t alignSizeWholePage(const void *ptr, size_t size) {
}
template <size_t alignment, typename T>
inline bool isAligned(T ptr) {
auto p = (uintptr_t)ptr;
return (p % alignment) == 0;
inline constexpr bool isAligned(T val) {
return (static_cast<size_t>(val) % alignment) == 0;
}
template <size_t alignment, typename T>
inline bool isAligned(T *ptr) {
return ((reinterpret_cast<uintptr_t>(ptr)) % alignment) == 0;
}
template <typename T>

View File

@ -264,3 +264,18 @@ TYPED_TEST(IsAlignedTests, aligned) {
auto ptr3 = reinterpret_cast<TypeParam *>(reinterpret_cast<uintptr_t>(ptr) & ~((alignof(TypeParam) >> 1) - 1));
EXPECT_FALSE(isAligned(ptr3));
}
TEST(IsAligned, nonPointerType) {
EXPECT_TRUE(isAligned<3>(0));
EXPECT_FALSE(isAligned<3>(1));
EXPECT_FALSE(isAligned<3>(2));
EXPECT_TRUE(isAligned<3>(3));
EXPECT_FALSE(isAligned<3>(4));
EXPECT_FALSE(isAligned<3>(5));
EXPECT_TRUE(isAligned<3>(6));
}
TEST(IsAligned, supportsConstexprEvaluation) {
static_assert(false == isAligned<3>(2), "");
static_assert(true == isAligned<3>(3), "");
}