// SPDX-FileCopyrightText: 2014 Jannik Vogel // SPDX-License-Identifier: CC0-1.0 #pragma once #include #include #include #include namespace Common { template requires std::is_integral_v [[nodiscard]] constexpr T AlignUp(T value, size_t size) { auto mod{static_cast(value % size)}; value -= mod; return static_cast(mod == T{0} ? value : value + size); } template requires std::is_unsigned_v [[nodiscard]] constexpr T AlignUpLog2(T value, size_t align_log2) { return static_cast((value + ((1ULL << align_log2) - 1)) >> align_log2 << align_log2); } template requires std::is_integral_v [[nodiscard]] constexpr T AlignDown(T value, size_t size) { return static_cast(value - value % size); } template requires std::is_unsigned_v [[nodiscard]] constexpr bool Is4KBAligned(T value) { return (value & 0xFFF) == 0; } template requires std::is_unsigned_v [[nodiscard]] constexpr bool IsWordAligned(T value) { return (value & 0b11) == 0; } template requires std::is_integral_v [[nodiscard]] constexpr bool IsAligned(T value, size_t alignment) { using U = typename std::make_unsigned_t; const U mask = static_cast(alignment - 1); return (value & mask) == 0; } template requires std::is_integral_v [[nodiscard]] constexpr T DivideUp(T x, U y) { return (x + (y - 1)) / y; } template requires std::is_integral_v [[nodiscard]] constexpr T LeastSignificantOneBit(T x) { return x & ~(x - 1); } template requires std::is_integral_v [[nodiscard]] constexpr T ResetLeastSignificantOneBit(T x) { return x & (x - 1); } template requires std::is_integral_v [[nodiscard]] constexpr bool IsPowerOfTwo(T x) { return x > 0 && ResetLeastSignificantOneBit(x) == 0; } template requires std::is_integral_v [[nodiscard]] constexpr T FloorPowerOfTwo(T x) { return T{1} << (sizeof(T) * 8 - std::countl_zero(x) - 1); } template class AlignmentAllocator { public: using value_type = T; using size_type = size_t; using difference_type = 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::false_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; }; template constexpr bool operator==(const AlignmentAllocator&) const noexcept { return std::is_same_v && Align == Align2; } }; } // namespace Common