FZGPUModules 2.0
GPU-accelerated modular compression pipelines
Loading...
Searching...
No Matches
zigzag.h
Go to the documentation of this file.
1#pragma once
2
30#include <cstdint>
31#include <type_traits>
32
33// nvcc defines __CUDACC__; hipcc/amdclang++ defines __HIPCC__ instead. Without
34// the second arm these helpers stay host-only under HIP and every __global__
35// caller fails to resolve them.
36#if defined(__CUDACC__) || defined(__HIPCC__)
37# define FZ_HOST_DEVICE __host__ __device__
38#else
39# define FZ_HOST_DEVICE
40#endif
41
42namespace fz {
43
56template <typename T>
57struct Zigzag {
58 static_assert(std::is_integral<T>::value && std::is_signed<T>::value,
59 "fz::Zigzag<T>: T must be a signed integer type "
60 "(int8_t, int16_t, int32_t, or int64_t).");
61
62 using SInt = T;
63 using UInt = typename std::make_unsigned<T>::type;
64
65 static constexpr int W = sizeof(T) * 8;
66
73 FZ_HOST_DEVICE static constexpr UInt encode(SInt x) noexcept {
74 // Cast to unsigned before shift to avoid UB on signed overflow,
75 // then XOR with the arithmetic right-shift mask.
76 return (static_cast<UInt>(x) << 1) ^ static_cast<UInt>(x >> (W - 1));
77 }
78
83 FZ_HOST_DEVICE static constexpr SInt decode(UInt u) noexcept {
84 // (u >> 1) reverses the shift; -(u & 1) reconstructs the sign mask.
85 // Cast to signed only at the final XOR to keep arithmetic well-defined.
86 return static_cast<SInt>((u >> 1) ^ static_cast<UInt>(-(static_cast<SInt>(u & 1u))));
87 }
88};
89
90// ---------------------------------------------------------------------------
91// Convenience aliases for the four standard widths
92// ---------------------------------------------------------------------------
93using Zigzag8 = Zigzag<int8_t>;
94using Zigzag16 = Zigzag<int16_t>;
95using Zigzag32 = Zigzag<int32_t>;
96using Zigzag64 = Zigzag<int64_t>;
97
98} // namespace fz
99
100#undef FZ_HOST_DEVICE
Definition algorithms.h:48
Definition zigzag.h:57
static FZ_HOST_DEVICE constexpr SInt decode(UInt u) noexcept
Definition zigzag.h:83
static FZ_HOST_DEVICE constexpr UInt encode(SInt x) noexcept
Definition zigzag.h:73