zigzag.h 870 B

123456789101112131415161718192021222324
  1. #pragma once
  2. #include "traits.h"
  3. namespace NYsonPull {
  4. namespace NDetail {
  5. namespace NZigZag {
  6. //! Functions that provide coding of integers with property: 0 <= f(x) <= 2 * |x|
  7. template <typename TSigned>
  8. inline NTraits::to_unsigned<TSigned> encode(TSigned x) {
  9. using TUnsigned = NTraits::to_unsigned<TSigned>;
  10. constexpr auto rshift = sizeof(TSigned) * 8 - 1;
  11. return (static_cast<TUnsigned>(x) << 1) ^ static_cast<TUnsigned>(x >> rshift);
  12. }
  13. template <typename TUnsigned>
  14. inline NTraits::to_signed<TUnsigned> decode(TUnsigned x) {
  15. using TSigned = NTraits::to_signed<TUnsigned>;
  16. return static_cast<TSigned>(x >> 1) ^ -static_cast<TSigned>(x & 1);
  17. }
  18. }
  19. } // namespace NDetail
  20. }