zig_zag-inl.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #ifndef ZIG_ZAG_INL_H_
  2. #error "Direct inclusion of this file is not allowed, include zig_zag.h"
  3. // For the sake of sane code completion.
  4. #include "zig_zag.h"
  5. #endif
  6. #undef ZIG_ZAG_INL_H_
  7. namespace NYT {
  8. ////////////////////////////////////////////////////////////////////////////////
  9. inline ui32 ZigZagEncode32(i32 n)
  10. {
  11. // Note: the right-shift must be arithmetic.
  12. // Note: left shift must be unsigned because of overflow.
  13. return (static_cast<ui32>(n) << 1) ^ static_cast<ui32>(n >> 31);
  14. }
  15. inline i32 ZigZagDecode32(ui32 n)
  16. {
  17. // Note: using unsigned types prevent undefined behavior.
  18. return static_cast<i32>((n >> 1) ^ (~(n & 1) + 1));
  19. }
  20. inline ui64 ZigZagEncode64(i64 n)
  21. {
  22. // Note: the right-shift must be arithmetic.
  23. // Note: left shift must be unsigned because of overflow.
  24. return (static_cast<ui64>(n) << 1) ^ static_cast<ui64>(n >> 63);
  25. }
  26. inline i64 ZigZagDecode64(ui64 n)
  27. {
  28. // Note: using unsigned types prevent undefined behavior.
  29. return static_cast<i64>((n >> 1) ^ (~(n & 1) + 1));
  30. }
  31. ////////////////////////////////////////////////////////////////////////////////
  32. } // namespace NYT