// `cuda/cmath` for NVRTC, which ships no device headers (see README.md).
// `cuda::fast_mod_div<unsigned>`: the one CCCL division `attn/fa2/fastdiv.cuh`
// reaches.

#pragma once

namespace cuda {

template <class _Tp, bool _DivisorIsNeverOne = false>
class fast_mod_div {
    static_assert(sizeof(_Tp) == 4 && static_cast<_Tp>(-1) > static_cast<_Tp>(0),
                  "pie shim: cuda::fast_mod_div is implemented for 32-bit unsigned types only "
                  "-- the multiply-high proof is a proof about dividends below 2^32. "
                  "Widen it deliberately, with a test, or use the built-in operator.");

public:
    fast_mod_div() = delete;

    __host__ __device__ explicit fast_mod_div(_Tp __divisor) noexcept : __divisor_(__divisor) {
        const unsigned long long __all_ones = ~0ull;
        const unsigned long long __q = __all_ones / __divisor;
        const unsigned long long __r = __all_ones % __divisor;
        __magic_ = __q + ((__r + 1ull == static_cast<unsigned long long>(__divisor)) ? 1ull : 0ull) + 1ull;
    }

    template <class _Up>
    [[nodiscard]] __host__ __device__ friend _Tp operator/(_Up __dividend,
                                                           fast_mod_div __divisor) noexcept {
        static_assert(sizeof(_Up) <= 4,
                      "pie shim: cuda::fast_mod_div divides 32-bit dividends. A wider one would "
                      "silently leave the range the multiply-high is exact on.");
        const unsigned int __n = static_cast<unsigned int>(__dividend);
#ifdef __CUDA_ARCH__
        if (!_DivisorIsNeverOne && __divisor.__divisor_ == 1u) {
            return static_cast<_Tp>(__n);
        }
        return static_cast<_Tp>(__umul64hi(static_cast<unsigned long long>(__n), __divisor.__magic_));
#else
        return static_cast<_Tp>(__n / __divisor.__divisor_);
#endif
    }

private:
    _Tp __divisor_;
    unsigned long long __magic_;
};

static_assert(sizeof(fast_mod_div<unsigned int>) == 16,
              "pie shim: fast_mod_div is 16 bytes -- a mirror pinned on that size "
              "is why this is asserted rather than assumed");
static_assert(alignof(fast_mod_div<unsigned int>) == 8,
              "pie shim: fast_mod_div aligns to 8 because of its 64-bit magic, "
              "where CCCL's aligns to 4 -- see the note above; a mirror that "
              "assumed CCCL's alignment reads the wrong bytes of every struct "
              "that embeds one");

}  // namespace cuda
