cuda::overflow_cast#

template <class T>
struct overflow_result;

template <class To, class From>
[[nodiscard]] __host__ __device__ inline constexpr
overflow_result<To> saturate_overflow_cast(From from) noexcept;

The function cuda::saturate_overflow_cast does saturating cast of a value of type From to type To with overflow checking.

Parameters

  • from: The value to be casted.

Return value

  • Returns an overflow_result object that contains the result of the saturating cast and a boolean indicating whether an overflow occurred.

Constraints

Example#

#include <cuda/numeric>
#include <cuda/std/cassert>
#include <cuda/std/limits>

__global__ void kernel()
{
    constexpr auto int_max = cuda::std::numeric_limits<int>::max();
    constexpr auto int_min = cuda::std::numeric_limits<int>::min();

    if (auto result = cuda::saturate_overflow_cast<unsigned>(int_max))
    {
        assert(false); // Should not be reached
    }
    else
    {
        assert(result.value == static_cast<unsigned>(int_max));
    }

    if (auto result = cuda::saturate_overflow_cast<unsigned>(int_min)) // saturated
    {
        assert(result.value == 0);
    }
    else
    {
        assert(false); // Should not be reached
    }
}

int main()
{
    kernel<<<1, 1>>>();
    cudaDeviceSynchronize();
}

See it on Godbolt 🔗