zigzag.h 893 B

12345678910111213141516171819202122232425262728293031
  1. #pragma once
  2. #include <util/system/defaults.h>
  3. namespace NYson {
  4. ////////////////////////////////////////////////////////////////////////////////
  5. //! Functions that provide coding of integers with property: 0 <= f(x) <= 2 * |x|
  6. //! Actually taken 'as is' from protobuf/wire_format_lite.h
  7. inline ui32 ZigZagEncode32(i32 n) {
  8. // Note: the right-shift must be arithmetic
  9. return (ui32(n) << 1) ^ (n >> 31);
  10. }
  11. inline i32 ZigZagDecode32(ui32 n) {
  12. return (n >> 1) ^ -static_cast<i32>(n & 1);
  13. }
  14. inline ui64 ZigZagEncode64(i64 n) {
  15. // Note: the right-shift must be arithmetic
  16. return (ui64(n) << 1) ^ (n >> 63);
  17. }
  18. inline i64 ZigZagDecode64(ui64 n) {
  19. return (n >> 1) ^ -static_cast<i64>(n & 1);
  20. }
  21. ////////////////////////////////////////////////////////////////////////////////
  22. } // namespace NYson