alignment.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. [[nodiscard]] constexpr T AlignUp(T value, std::size_t size) {
  9. static_assert(std::is_unsigned_v<T>, "T must be an unsigned value.");
  10. auto mod{static_cast<T>(value % size)};
  11. value -= mod;
  12. return static_cast<T>(mod == T{0} ? value : value + size);
  13. }
  14. template <typename T>
  15. [[nodiscard]] constexpr T AlignDown(T value, std::size_t size) {
  16. static_assert(std::is_unsigned_v<T>, "T must be an unsigned value.");
  17. return static_cast<T>(value - value % size);
  18. }
  19. template <typename T>
  20. [[nodiscard]] constexpr T AlignBits(T value, std::size_t align) {
  21. static_assert(std::is_unsigned_v<T>, "T must be an unsigned value.");
  22. return static_cast<T>((value + ((1ULL << align) - 1)) >> align << align);
  23. }
  24. template <typename T>
  25. [[nodiscard]] constexpr bool Is4KBAligned(T value) {
  26. static_assert(std::is_unsigned_v<T>, "T must be an unsigned value.");
  27. return (value & 0xFFF) == 0;
  28. }
  29. template <typename T>
  30. [[nodiscard]] constexpr bool IsWordAligned(T value) {
  31. static_assert(std::is_unsigned_v<T>, "T must be an unsigned value.");
  32. return (value & 0b11) == 0;
  33. }
  34. template <typename T>
  35. [[nodiscard]] constexpr bool IsAligned(T value, std::size_t alignment) {
  36. using U = typename std::make_unsigned<T>::type;
  37. const U mask = static_cast<U>(alignment - 1);
  38. return (value & mask) == 0;
  39. }
  40. template <typename T, std::size_t Align = 16>
  41. class AlignmentAllocator {
  42. public:
  43. using value_type = T;
  44. using size_type = std::size_t;
  45. using difference_type = std::ptrdiff_t;
  46. using propagate_on_container_copy_assignment = std::true_type;
  47. using propagate_on_container_move_assignment = std::true_type;
  48. using propagate_on_container_swap = std::true_type;
  49. using is_always_equal = std::true_type;
  50. constexpr AlignmentAllocator() noexcept = default;
  51. template <typename T2>
  52. constexpr AlignmentAllocator(const AlignmentAllocator<T2, Align>&) noexcept {}
  53. [[nodiscard]] T* allocate(size_type n) {
  54. return static_cast<T*>(::operator new (n * sizeof(T), std::align_val_t{Align}));
  55. }
  56. void deallocate(T* p, size_type n) {
  57. ::operator delete (p, n * sizeof(T), std::align_val_t{Align});
  58. }
  59. template <typename T2>
  60. struct rebind {
  61. using other = AlignmentAllocator<T2, Align>;
  62. };
  63. };
  64. } // namespace Common