Alignment.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* Copyright The kNet Project.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License. */
  11. #pragma once
  12. /** @file Alignment.h
  13. @brief Provides functions for working with pointer data alignment computations.*/
  14. #include <cassert>
  15. #include "Types.h"
  16. #if defined(KNET_UNIX) || defined(ANDROID)
  17. #include <stdint.h>
  18. #endif
  19. namespace kNet
  20. {
  21. /// Is value an exact power of 2? i.e. 1,2,4,8,16,...
  22. #define IS_POW2(value) (((value) & ((value)-1)) == 0)
  23. /// Is the given pointer aligned to the pow2-boundary specified by alignment?
  24. inline bool IsPow2Aligned(uintptr_t pointer, u32 alignment)
  25. {
  26. assert(IS_POW2(alignment));
  27. return (pointer & (alignment - 1)) == 0;
  28. }
  29. /// @return The given pointer aligned up to the next pow2-boundary specified by alignment. (Alignment must be a pow2)
  30. inline uintptr_t AlignUpPow2(uintptr_t pointer, u32 alignment)
  31. {
  32. assert(IS_POW2(alignment));
  33. return (pointer + alignment - 1) & ~((uintptr_t)alignment - 1);
  34. }
  35. /// @return The given pointer aligned down to the previous pow2-boundary specified by alignment. (Alignment must be a pow2)
  36. inline uintptr_t AlignDownPow2(uintptr_t pointer, u32 alignment)
  37. {
  38. assert(IS_POW2(alignment));
  39. return pointer & ~((uintptr_t)alignment - 1);
  40. }
  41. inline u32 RoundUpToNextPow2(u32 x)
  42. {
  43. x = x - 1;
  44. x = x | (x >> 1);
  45. x = x | (x >> 2);
  46. x = x | (x >> 4);
  47. x = x | (x >> 8);
  48. x = x | (x >> 16);
  49. return x + 1;
  50. }
  51. inline u64 RoundUpToNextPow2(u64 x)
  52. {
  53. x = x - 1;
  54. x = x | (x >> 1);
  55. x = x | (x >> 2);
  56. x = x | (x >> 4);
  57. x = x | (x >> 8);
  58. x = x | (x >> 16);
  59. x = x | (x >> 32);
  60. return x + 1;
  61. }
  62. } // ~kNet