shogo-library

競技プログラミング用の C++ ライブラリ

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: test/unittest/math/saturating.test.cpp

Depends on

Code

#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"

// saturating.hpp の関数を、__int128 で計算して範囲に丸めたものと比較する
// 8 ビットの型は全組、それ以外は境界付近の値とランダムな値で調べる
// 問題の入力は使わず、すべて一致したら Hello World を出力する

#include "../../../src/math/saturating.hpp"

#include <cstdint>
#include <iostream>
#include <limits>
#include <random>
#include <type_traits>
#include <utility>
#include <vector>

using i128 = __int128;
using u128 = unsigned __int128;

bool ok = true;

void check(bool cond, const char* what) {
    if (!cond) {
        if (ok) std::cerr << "failed: " << what << std::endl;
        ok = false;
    }
}

template <class T>
i128 lo() { return static_cast<i128>(std::numeric_limits<T>::min()); }
template <class T>
i128 hi() { return static_cast<i128>(std::numeric_limits<T>::max()); }
template <class T>
T clamp128(i128 v) { return v < lo<T>() ? std::numeric_limits<T>::min() : v > hi<T>() ? std::numeric_limits<T>::max()
                                                                                      : static_cast<T>(v); }

// 境界付近の値とランダムな値
template <class T>
std::vector<T> samples(std::mt19937_64& rng) {
    std::vector<T> res;
    for (i128 d = 0; d < 4; d++) {
        for (i128 v : {lo<T>() + d, hi<T>() - d, d, -d, hi<T>() / 2 - 1 + d, lo<T>() / 2 - 1 + d}) {
            if (lo<T>() <= v && v <= hi<T>()) res.push_back(static_cast<T>(v));
        }
    }
    for (int i = 0; i < 40; i++) {
        T v = static_cast<T>(rng());
        res.push_back(v);
        res.push_back(static_cast<T>(v >> (rng() % (8 * sizeof(T)))));  // 小さい値も混ぜる
    }
    return res;
}

template <class T>
void check_arith(const std::vector<T>& xs) {
    for (T x : xs) {
        for (T y : xs) {
            check(saturating_add(x, y) == clamp128<T>(static_cast<i128>(x) + y), "saturating_add");
            check(saturating_sub(x, y) == clamp128<T>(static_cast<i128>(x) - y), "saturating_sub");
            if constexpr (std::is_unsigned_v<T> && sizeof(T) == 8) {
                u128 p = static_cast<u128>(x) * y;
                check(saturating_mul(x, y) == (p > static_cast<u128>(std::numeric_limits<T>::max()) ? std::numeric_limits<T>::max() : static_cast<T>(p)), "saturating_mul");
            } else {
                check(saturating_mul(x, y) == clamp128<T>(static_cast<i128>(x) * y), "saturating_mul");
            }
            if (y != 0) check(saturating_div(x, y) == clamp128<T>(static_cast<i128>(x) / y), "saturating_div");
            static_assert(std::is_same_v<decltype(saturating_add(x, y)), T>);
        }
    }
}

template <class R, class T>
void check_cast(const std::vector<T>& xs) {
    for (T x : xs) check(saturating_cast<R>(x) == clamp128<R>(static_cast<i128>(x)), "saturating_cast");
    static_assert(std::is_same_v<decltype(saturating_cast<R>(T())), R>);
}
template <class T, class... Rs>
void check_cast_all(std::mt19937_64& rng) {
    auto xs = samples<T>(rng);
    (check_cast<Rs>(xs), ...);
}

// 整数型以外を渡すと候補から外れる (bool、文字型、浮動小数点数)
template <class T, class = void>
struct can_add : std::false_type {};
template <class T>
struct can_add<T, std::void_t<decltype(saturating_add(std::declval<T>(), std::declval<T>()))>> : std::true_type {};
template <class R, class T, class = void>
struct can_cast : std::false_type {};
template <class R, class T>
struct can_cast<R, T, std::void_t<decltype(saturating_cast<R>(std::declval<T>()))>> : std::true_type {};

static_assert(can_add<int>::value && can_add<unsigned long long>::value && can_add<std::int8_t>::value);
static_assert(!can_add<bool>::value && !can_add<char>::value && !can_add<char32_t>::value && !can_add<double>::value);
static_assert(can_cast<int, long long>::value && !can_cast<bool, int>::value && !can_cast<int, double>::value);

// constexpr の中でも使える
static_assert(saturating_add(100, 2000000000) == 2000000100);
static_assert(saturating_add(2000000000, 2000000000) == std::numeric_limits<int>::max());
static_assert(saturating_sub(0u, 1u) == 0u);
static_assert(saturating_mul(-3000000000LL, 4000000000LL) == std::numeric_limits<long long>::min());
static_assert(saturating_div(std::numeric_limits<int>::min(), -1) == std::numeric_limits<int>::max());
static_assert(saturating_cast<std::uint8_t>(-5) == 0 && saturating_cast<std::uint8_t>(300) == 255);
static_assert(saturating_cast<int>(std::numeric_limits<unsigned long long>::max()) == std::numeric_limits<int>::max());

int main() {
    std::mt19937_64 rng(314);

    // 8 ビットの型は全組
    {
        std::vector<std::int8_t> s;
        std::vector<std::uint8_t> u;
        for (int v = -128; v < 128; v++) s.push_back(static_cast<std::int8_t>(v));
        for (int v = 0; v < 256; v++) u.push_back(static_cast<std::uint8_t>(v));
        check_arith(s);
        check_arith(u);
    }
    check_arith(samples<short>(rng));
    check_arith(samples<unsigned short>(rng));
    check_arith(samples<int>(rng));
    check_arith(samples<unsigned>(rng));
    check_arith(samples<long>(rng));
    check_arith(samples<long long>(rng));
    check_arith(samples<unsigned long long>(rng));

#define CAST_TYPES std::int8_t, std::uint8_t, short, unsigned short, int, unsigned, long long, unsigned long long
    check_cast_all<std::int8_t, CAST_TYPES>(rng);
    check_cast_all<std::uint8_t, CAST_TYPES>(rng);
    check_cast_all<short, CAST_TYPES>(rng);
    check_cast_all<unsigned short, CAST_TYPES>(rng);
    check_cast_all<int, CAST_TYPES>(rng);
    check_cast_all<unsigned, CAST_TYPES>(rng);
    check_cast_all<long long, CAST_TYPES>(rng);
    check_cast_all<unsigned long long, CAST_TYPES>(rng);

    if (ok) std::cout << "Hello World" << std::endl;
}
#line 1 "test/unittest/math/saturating.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"

// saturating.hpp の関数を、__int128 で計算して範囲に丸めたものと比較する
// 8 ビットの型は全組、それ以外は境界付近の値とランダムな値で調べる
// 問題の入力は使わず、すべて一致したら Hello World を出力する

#line 2 "src/math/saturating.hpp"

/**
 * @file saturating.hpp
 * @brief 飽和演算 (結果が型の範囲を超えたら、その型の最大値・最小値に丸める)
 */

#include <cassert>
#include <limits>
#include <numeric>
#include <type_traits>
#include <utility>

#if __cplusplus >= 202002L
#include <concepts>
#endif

namespace internal_saturating {
template <class T>
struct is_character : std::false_type {};
template <>
struct is_character<char> : std::true_type {};
template <>
struct is_character<wchar_t> : std::true_type {};
template <>
struct is_character<char16_t> : std::true_type {};
template <>
struct is_character<char32_t> : std::true_type {};
#ifdef __cpp_char8_t
template <>
struct is_character<char8_t> : std::true_type {};
#endif

// bool と文字型を除く整数型 (C++26 の std::add_sat などと同じ条件)
#if __cplusplus >= 202002L
template <class T>
concept integer = std::integral<T> && !std::same_as<std::remove_cv_t<T>, bool> && !is_character<std::remove_cv_t<T>>::value;

using std::cmp_greater;
using std::cmp_less;
#else
template <class T>
inline constexpr bool integer = std::is_integral_v<T> && !std::is_same_v<std::remove_cv_t<T>, bool> && !is_character<std::remove_cv_t<T>>::value;

// C++20 の std::cmp_less と同じ (符号の有無が違っても値として比べる)
template <class T, class U>
constexpr bool cmp_less(T t, U u) noexcept {
    if constexpr (std::is_signed_v<T> == std::is_signed_v<U>) {
        return t < u;
    } else if constexpr (std::is_signed_v<T>) {
        return t < 0 || std::make_unsigned_t<T>(t) < u;
    } else {
        return u >= 0 && t < std::make_unsigned_t<U>(u);
    }
}
template <class T, class U>
constexpr bool cmp_greater(T t, U u) noexcept {
    return cmp_less(u, t);
}
#endif
}  // namespace internal_saturating

// C++20 では requires で、C++17 では戻り値の enable_if で整数型に制限する
#if __cplusplus >= 202002L
#define SATURATING_FUNC(cond, R) requires(cond) inline constexpr R
#else
#define SATURATING_FUNC(cond, R) inline constexpr std::enable_if_t<(cond), R>
#endif

// clang-format は SATURATING_FUNC を戻り値の型と読めず、関数名の前で改行してしまうので整形しない
// clang-format off

/**
 * @brief x + y を T の範囲に丸める
 */
template <class T>
SATURATING_FUNC(internal_saturating::integer<T>, T) saturating_add(T x, T y) noexcept {
#ifdef __cpp_lib_saturation_arithmetic
    return std::add_sat(x, y);
#else
    T res{};
    if (!__builtin_add_overflow(x, y, &res)) return res;
    if constexpr (std::is_signed_v<T>) {
        if (y < 0) return std::numeric_limits<T>::min();
    }
    return std::numeric_limits<T>::max();
#endif
}
/**
 * @brief x - y を T の範囲に丸める
 */
template <class T>
SATURATING_FUNC(internal_saturating::integer<T>, T) saturating_sub(T x, T y) noexcept {
#ifdef __cpp_lib_saturation_arithmetic
    return std::sub_sat(x, y);
#else
    T res{};
    if (!__builtin_sub_overflow(x, y, &res)) return res;
    if constexpr (std::is_signed_v<T>) {
        if (y < 0) return std::numeric_limits<T>::max();
    }
    return std::numeric_limits<T>::min();
#endif
}
/**
 * @brief x * y を T の範囲に丸める
 */
template <class T>
SATURATING_FUNC(internal_saturating::integer<T>, T) saturating_mul(T x, T y) noexcept {
#ifdef __cpp_lib_saturation_arithmetic
    return std::mul_sat(x, y);
#else
    T res{};
    if (!__builtin_mul_overflow(x, y, &res)) return res;
    if constexpr (std::is_signed_v<T>) {
        if ((x < 0) != (y < 0)) return std::numeric_limits<T>::min();
    }
    return std::numeric_limits<T>::max();
#endif
}
/**
 * @brief x / y (0 方向に切り捨て) を T の範囲に丸める (y != 0)
 * あふれるのは符号付きの min / -1 だけで、max を返す
 */
template <class T>
SATURATING_FUNC(internal_saturating::integer<T>, T) saturating_div(T x, T y) noexcept {
    assert(y != 0);
#ifdef __cpp_lib_saturation_arithmetic
    return std::div_sat(x, y);
#else
    if constexpr (std::is_signed_v<T>) {
        if (x == std::numeric_limits<T>::min() && y == -1) return std::numeric_limits<T>::max();
    }
    return x / y;
#endif
}
/**
 * @brief 整数 x を R に変換し、R の範囲に収まらなければ R の最大値・最小値に丸める
 */
template <class R, class T>
SATURATING_FUNC(internal_saturating::integer<R> && internal_saturating::integer<T>, R) saturating_cast(T x) noexcept {
#ifdef __cpp_lib_saturation_arithmetic
    return std::saturate_cast<R>(x);
#else
    if (internal_saturating::cmp_less(x, std::numeric_limits<R>::min())) return std::numeric_limits<R>::min();
    if (internal_saturating::cmp_greater(x, std::numeric_limits<R>::max())) return std::numeric_limits<R>::max();
    return static_cast<R>(x);
#endif
}

// clang-format on

#undef SATURATING_FUNC
#line 8 "test/unittest/math/saturating.test.cpp"

#include <cstdint>
#include <iostream>
#line 12 "test/unittest/math/saturating.test.cpp"
#include <random>
#line 15 "test/unittest/math/saturating.test.cpp"
#include <vector>

using i128 = __int128;
using u128 = unsigned __int128;

bool ok = true;

void check(bool cond, const char* what) {
    if (!cond) {
        if (ok) std::cerr << "failed: " << what << std::endl;
        ok = false;
    }
}

template <class T>
i128 lo() { return static_cast<i128>(std::numeric_limits<T>::min()); }
template <class T>
i128 hi() { return static_cast<i128>(std::numeric_limits<T>::max()); }
template <class T>
T clamp128(i128 v) { return v < lo<T>() ? std::numeric_limits<T>::min() : v > hi<T>() ? std::numeric_limits<T>::max()
                                                                                      : static_cast<T>(v); }

// 境界付近の値とランダムな値
template <class T>
std::vector<T> samples(std::mt19937_64& rng) {
    std::vector<T> res;
    for (i128 d = 0; d < 4; d++) {
        for (i128 v : {lo<T>() + d, hi<T>() - d, d, -d, hi<T>() / 2 - 1 + d, lo<T>() / 2 - 1 + d}) {
            if (lo<T>() <= v && v <= hi<T>()) res.push_back(static_cast<T>(v));
        }
    }
    for (int i = 0; i < 40; i++) {
        T v = static_cast<T>(rng());
        res.push_back(v);
        res.push_back(static_cast<T>(v >> (rng() % (8 * sizeof(T)))));  // 小さい値も混ぜる
    }
    return res;
}

template <class T>
void check_arith(const std::vector<T>& xs) {
    for (T x : xs) {
        for (T y : xs) {
            check(saturating_add(x, y) == clamp128<T>(static_cast<i128>(x) + y), "saturating_add");
            check(saturating_sub(x, y) == clamp128<T>(static_cast<i128>(x) - y), "saturating_sub");
            if constexpr (std::is_unsigned_v<T> && sizeof(T) == 8) {
                u128 p = static_cast<u128>(x) * y;
                check(saturating_mul(x, y) == (p > static_cast<u128>(std::numeric_limits<T>::max()) ? std::numeric_limits<T>::max() : static_cast<T>(p)), "saturating_mul");
            } else {
                check(saturating_mul(x, y) == clamp128<T>(static_cast<i128>(x) * y), "saturating_mul");
            }
            if (y != 0) check(saturating_div(x, y) == clamp128<T>(static_cast<i128>(x) / y), "saturating_div");
            static_assert(std::is_same_v<decltype(saturating_add(x, y)), T>);
        }
    }
}

template <class R, class T>
void check_cast(const std::vector<T>& xs) {
    for (T x : xs) check(saturating_cast<R>(x) == clamp128<R>(static_cast<i128>(x)), "saturating_cast");
    static_assert(std::is_same_v<decltype(saturating_cast<R>(T())), R>);
}
template <class T, class... Rs>
void check_cast_all(std::mt19937_64& rng) {
    auto xs = samples<T>(rng);
    (check_cast<Rs>(xs), ...);
}

// 整数型以外を渡すと候補から外れる (bool、文字型、浮動小数点数)
template <class T, class = void>
struct can_add : std::false_type {};
template <class T>
struct can_add<T, std::void_t<decltype(saturating_add(std::declval<T>(), std::declval<T>()))>> : std::true_type {};
template <class R, class T, class = void>
struct can_cast : std::false_type {};
template <class R, class T>
struct can_cast<R, T, std::void_t<decltype(saturating_cast<R>(std::declval<T>()))>> : std::true_type {};

static_assert(can_add<int>::value && can_add<unsigned long long>::value && can_add<std::int8_t>::value);
static_assert(!can_add<bool>::value && !can_add<char>::value && !can_add<char32_t>::value && !can_add<double>::value);
static_assert(can_cast<int, long long>::value && !can_cast<bool, int>::value && !can_cast<int, double>::value);

// constexpr の中でも使える
static_assert(saturating_add(100, 2000000000) == 2000000100);
static_assert(saturating_add(2000000000, 2000000000) == std::numeric_limits<int>::max());
static_assert(saturating_sub(0u, 1u) == 0u);
static_assert(saturating_mul(-3000000000LL, 4000000000LL) == std::numeric_limits<long long>::min());
static_assert(saturating_div(std::numeric_limits<int>::min(), -1) == std::numeric_limits<int>::max());
static_assert(saturating_cast<std::uint8_t>(-5) == 0 && saturating_cast<std::uint8_t>(300) == 255);
static_assert(saturating_cast<int>(std::numeric_limits<unsigned long long>::max()) == std::numeric_limits<int>::max());

int main() {
    std::mt19937_64 rng(314);

    // 8 ビットの型は全組
    {
        std::vector<std::int8_t> s;
        std::vector<std::uint8_t> u;
        for (int v = -128; v < 128; v++) s.push_back(static_cast<std::int8_t>(v));
        for (int v = 0; v < 256; v++) u.push_back(static_cast<std::uint8_t>(v));
        check_arith(s);
        check_arith(u);
    }
    check_arith(samples<short>(rng));
    check_arith(samples<unsigned short>(rng));
    check_arith(samples<int>(rng));
    check_arith(samples<unsigned>(rng));
    check_arith(samples<long>(rng));
    check_arith(samples<long long>(rng));
    check_arith(samples<unsigned long long>(rng));

#define CAST_TYPES std::int8_t, std::uint8_t, short, unsigned short, int, unsigned, long long, unsigned long long
    check_cast_all<std::int8_t, CAST_TYPES>(rng);
    check_cast_all<std::uint8_t, CAST_TYPES>(rng);
    check_cast_all<short, CAST_TYPES>(rng);
    check_cast_all<unsigned short, CAST_TYPES>(rng);
    check_cast_all<int, CAST_TYPES>(rng);
    check_cast_all<unsigned, CAST_TYPES>(rng);
    check_cast_all<long long, CAST_TYPES>(rng);
    check_cast_all<unsigned long long, CAST_TYPES>(rng);

    if (ok) std::cout << "Hello World" << std::endl;
}
Back to top page