8000 Fix the int8 and int2 cases of (minimum possible integer) % (-1). · danielcode/postgres@3b4db79 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3b4db79

Browse files
committed
Fix the int8 and int2 cases of (minimum possible integer) % (-1).
The correct answer for this (or any other case with arg2 = -1) is zero, but some machines throw a floating-point exception instead of behaving sanely. Commit f9ac414 dealt with this in int4mod, but overlooked the fact that it also happens in int8mod (at least on my Linux x86_64 machine). Protect int2mod as well; it's not clear whether any machines fail there (mine does not) but since the test is so cheap it seems better safe than sorry. While at it, simplify the original guard in int4mod: we need only check for arg2 == -1, we don't need to check arg1 explicitly. Xi Wang, with some editing by me.
1 parent 5355e39 commit 3b4db79

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/backend/utils/adt/int.c

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1095,8 +1095,12 @@ int4mod(PG_FUNCTION_ARGS)
10951095
PG_RETURN_NULL();
10961096
}
10971097

1098-
/* SELECT ((-2147483648)::int4) % (-1); causes a floating point exception */
1099-
if (arg1 == INT_MIN && arg2 == -1)
1098+
/*
1099+
* Some machines throw a floating-point exception for INT_MIN % -1, which
1100+
* is a bit silly since the correct answer is perfectly well-defined,
1101+
* namely zero.
1102+
*/
1103+
if (arg2 == -1)
11001104
PG_RETURN_INT32(0);
11011105

11021106
/* No overflow is possible */
@@ -1119,6 +1123,15 @@ int2mod(PG_FUNCTION_ARGS)
11191123
PG_RETURN_NULL();
11201124
}
11211125

1126+
/*
1127+
* Some machines throw a floating-point exception for INT_MIN % -1, which
1128+
* is a bit silly since the correct answer is perfectly well-defined,
1129+
* namely zero. (It's not clear this ever happens when dealing with
1130+
* int16, but we might as well have the test for safety.)
1131+
*/
1132+
if (arg2 == -1)
1133+
PG_RETURN_INT16(0);
1134+
11221135
/* No overflow is possible */
11231136

11241137
PG_RETURN_INT16(arg1 % arg2);

src/backend/utils/adt/int8.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -649,6 +649,14 @@ int8mod(PG_FUNCTION_ARGS)
649649
PG_RETURN_NULL();
650650
}
651651

652+
/*
653+
* Some machines throw a floating-point exception for INT64_MIN % -1,
654+
* which is a bit silly since the correct answer is perfectly
655+
* well-defined, namely zero.
656+
*/
657+
if (arg2 == -1)
658+
PG_RETURN_INT64(0);
659+
652660
/* No overflow is possible */
653661

654662
PG_RETURN_INT64(arg1 % arg2);

0 commit comments

Comments
 (0)
0