mirror of
https://github.com/justinethier/cyclone.git
synced 2025-05-23 20:15:05 +02:00
Issue #276 - Improve overflow detection for multiplication
This commit is contained in:
parent
b2326b89f4
commit
b41971e187
1 changed files with 5 additions and 8 deletions
13
runtime.c
13
runtime.c
|
@ -3050,17 +3050,14 @@ static int Cyc_checked_sub(int x, int y, int *result)
|
|||
return ((((*result ^ x) & ~(*result ^ y)) >> 30) != 0);
|
||||
}
|
||||
|
||||
// Code from http://stackoverflow.com/q/1815367/101258
|
||||
static int Cyc_checked_mul(int x, int y, int *result)
|
||||
{
|
||||
// *result = x * y;
|
||||
// return (*result != 0 && (*result)/x != y) || // Overflow
|
||||
// (*result > CYC_FIXNUM_MAX) ||
|
||||
// (*result < CYC_FIXNUM_MIN);
|
||||
// Avoid undefined behavior by detecting overflow prior to multiplication
|
||||
// Based on code from Hacker's Delight and CHICKEN scheme
|
||||
uint xu, yu, c;
|
||||
c = 1UL<<31UL;
|
||||
xu = x < 0 ? -1 : x;
|
||||
yu = y < 0 ? -1 : y;
|
||||
c = (1UL<<30UL) - 1;
|
||||
xu = x < 0 ? -x : x;
|
||||
yu = y < 0 ? -y : y;
|
||||
|
||||
if (yu != 0 && xu > (c / yu)) return 1; // Overflow
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue