alignment.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // This file is under the public domain.
  2. #pragma once
  3. #include <cstddef>
  4. #include <new>
  5. #include <type_traits>
  6. namespace Common {
  7. template <typename T>
  8. requires std::is_unsigned_v<T>[[nodiscard]] constexpr T AlignUp(T value, size_t size) {
  9. auto mod{static_cast<T>(value % size)};
  10. value -= mod;
  11. return static_cast<T>(mod == T{0} ? value : value + size);
  12. }
  13. template <typename T>
  14. requires std::is_unsigned_v<T>[[nodiscard]] constexpr T AlignUpLog2(T value, size_t align_log2) {
  15. return static_cast<T>((value + ((1ULL << align_log2) - 1)) >> align_log2 << align_log2);
  16. }
  17. template <typename T>
  18. requires std::is_unsigned_v<T>[[nodiscard]] constexpr T AlignDown(T value, size_t size) {
  19. return static_cast<T>(value - value % size);
  20. }
  21. template <typename T>
  22. requires std::is_unsigned_v<T>[[nodiscard]] constexpr bool Is4KBAligned(T value) {
  23. return (value & 0xFFF) == 0;
  24. }
  25. template <typename T>
  26. requires std::is_unsigned_v<T>[[nodiscard]] constexpr bool IsWordAligned(T value) {
  27. return (value & 0b11) == 0;
  28. }
  29. template <typename T>
  30. requires std::is_integral_v<T>[[nodiscard]] constexpr bool IsAligned(T value, size_t alignment) {
  31. using U = typename std::make_unsigned_t<T>;
  32. const U mask = static_cast<U>(alignment - 1);
  33. return (value & mask) == 0;
  34. }
  35. template <typename T, size_t Align = 16>
  36. class AlignmentAllocator {
  37. public:
  38. using value_type = T;
  39. using size_type = size_t;
  40. using difference_type = ptrdiff_t;
  41. using propagate_on_container_copy_assignment = std::true_type;
  42. using propagate_on_container_move_assignment = std::true_type;
  43. using propagate_on_container_swap = std::true_type;
  44. using is_always_equal = std::true_type;
  45. constexpr AlignmentAllocator() noexcept = default;
  46. template <typename T2>
  47. constexpr AlignmentAllocator(const AlignmentAllocator<T2, Align>&) noexcept {}
  48. [[nodiscard]] T* allocate(size_type n) {
  49. return static_cast<T*>(::operator new (n * sizeof(T), std::align_val_t{Align}));
  50. }
  51. void deallocate(T* p, size_type n) {
  52. ::operator delete (p, n * sizeof(T), std::align_val_t{Align});
  53. }
  54. template <typename T2>
  55. struct rebind {
  56. using other = AlignmentAllocator<T2, Align>;
  57. };
  58. };
  59. } // namespace Common