/*
 * some overflow checking integer arithmetic
 */
#include <numpy/npy_common.h>

#ifndef __NPY_SCALARMATHMODULE_H__
#define __NPY_SCALARMATHMODULE_H__

/**begin repeat
 *  #name = int, uint, long, ulong,
 *          longlong, ulonglong, intp#
 *  #type = npy_int, npy_uint, npy_long, npy_ulong,
 *          npy_longlong, npy_ulonglong, npy_intp#
 *  #MAX = NPY_MAX_INT, NPY_MAX_UINT, NPY_MAX_LONG, NPY_MAX_ULONG,
 *         NPY_MAX_LONGLONG, NPY_MAX_ULONGLONG, NPY_MAX_INTP#
 */

/*
 * writes result of a * b into r
 * returns 1 if a * b overflowed else returns 0
 */
static NPY_INLINE int
npy_mul_with_overflow_@name@(@type@ * r, @type@ a, @type@ b)
{
    const @type@ half_sz = (((@type@)1 << (sizeof(a) * 8 / 2)) - 1);

    *r = a * b;
    /*
     * avoid expensive division on common no overflow case
     * could be improved via compiler intrinsics e.g. via clang
     * __builtin_mul_with_overflow, gcc __int128 or cpu overflow flags
     */
    if (NPY_UNLIKELY((a | b) >= half_sz) &&
        a != 0 && b > @MAX@ / a) {
        return 1;
    }

    return 0;
}
/**end repeat**/

#endif
