address.h: add pointer alignment functions

More explicit than address_cast and bitwise and
This commit is contained in:
Nathaniel Filardo
2019-05-07 13:21:02 +01:00
parent 20e804728b
commit ef7985510c
6 changed files with 40 additions and 11 deletions

View File

@@ -56,4 +56,35 @@ namespace snmalloc
0;
}
/**
* Align a pointer down to a statically specified granularity, which must be a
* power of two.
*/
template<size_t alignment, typename T = void>
inline T* pointer_align_down(void* p)
{
static_assert(alignment > 0);
static_assert(bits::next_pow2_const(alignment) == alignment);
#if __has_builtin(__builtin_align_down)
return static_cast<T*>(__builtin_align_down(p, alignment));
#else
return pointer_cast<T>(bits::align_down(address_cast(p), alignment));
#endif
}
/**
* Align a pointer up to a statically specified granularity, which must be a
* power of two.
*/
template<size_t alignment, typename T = void>
inline T* pointer_align_up(void* p)
{
static_assert(alignment > 0);
static_assert(bits::next_pow2_const(alignment) == alignment);
#if __has_builtin(__builtin_align_up)
return static_cast<T*>(__builtin_align_up(p, alignment));
#else
return pointer_cast<T>(bits::align_up(address_cast(p), alignment));
#endif
}
} // namespace snmalloc