align.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #pragma once
  2. #include "yassert.h"
  3. #include "defaults.h"
  4. #include <util/generic/bitops.h>
  5. template <class T>
  6. static inline T AlignDown(T len, T align) noexcept {
  7. Y_ASSERT(IsPowerOf2(align)); // align should be power of 2
  8. return len & ~(align - 1);
  9. }
  10. template <class T>
  11. static inline T AlignUp(T len, T align) noexcept {
  12. const T alignedResult = AlignDown(len + (align - 1), align);
  13. Y_ASSERT(alignedResult >= len); // check for overflow
  14. return alignedResult;
  15. }
  16. template <class T>
  17. static inline T AlignUpSpace(T len, T align) noexcept {
  18. Y_ASSERT(IsPowerOf2(align)); // align should be power of 2
  19. return ((T)0 - len) & (align - 1); // AlignUp(len, align) - len;
  20. }
  21. template <class T>
  22. static inline T* AlignUp(T* ptr, size_t align) noexcept {
  23. return (T*)AlignUp((uintptr_t)ptr, align);
  24. }
  25. template <class T>
  26. static inline T* AlignDown(T* ptr, size_t align) noexcept {
  27. return (T*)AlignDown((uintptr_t)ptr, align);
  28. }
  29. template <class T>
  30. static inline T AlignUp(T t) noexcept {
  31. return AlignUp(t, (size_t)PLATFORM_DATA_ALIGN);
  32. }
  33. template <class T>
  34. static inline T AlignDown(T t) noexcept {
  35. return AlignDown(t, (size_t)PLATFORM_DATA_ALIGN);
  36. }
  37. template <class T>
  38. static inline T Align(T t) noexcept {
  39. return AlignUp(t);
  40. }