// This file is under the public domain. #pragma once #include #include #include namespace Common { template [[nodiscard]] constexpr T AlignUp(T value, std::size_t size) { static_assert(std::is_unsigned_v, "T must be an unsigned value."); auto mod{static_cast(value % size)}; value -= mod; return static_cast(mod == T{0} ? value : value + size); } template [[nodiscard]] constexpr T AlignDown(T value, std::size_t size) { static_assert(std::is_unsigned_v, "T must be an unsigned value."); return static_cast(value - value % size); } template [[nodiscard]] constexpr T AlignBits(T value, std::size_t align) { static_assert(std::is_unsigned_v, "T must be an unsigned value."); return static_cast((value + ((1ULL << align) - 1)) >> align << align); } template [[nodiscard]] constexpr bool Is4KBAligned(T value) { static_assert(std::is_unsigned_v, "T must be an unsigned value."); return (value & 0xFFF) == 0; } template [[nodiscard]] constexpr bool IsWordAligned(T value) { static_assert(std::is_unsigned_v, "T must be an unsigned value."); return (value & 0b11) == 0; } template [[nodiscard]] constexpr bool IsAligned(T value, std::size_t alignment) { using U = typename std::make_unsigned::type; const U mask = static_cast(alignment - 1); return (value & mask) == 0; } template class AlignmentAllocator { public: using value_type = T; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using propagate_on_container_copy_assignment = std::true_type; using propagate_on_container_move_assignment = std::true_type; using propagate_on_container_swap = std::true_type; using is_always_equal = std::true_type; constexpr AlignmentAllocator() noexcept = default; template constexpr AlignmentAllocator(const AlignmentAllocator&) noexcept {} [[nodiscard]] T* allocate(size_type n) { return static_cast(::operator new (n * sizeof(T), std::align_val_t{Align})); } void deallocate(T* p, size_type n) { ::operator delete (p, n * sizeof(T), std::align_val_t{Align}); } template struct rebind { using other = AlignmentAllocator; }; }; } // namespace Common