Skip to content

Commit 46c79df

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 c027d84 commit 46c79df

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
@@ -1083,8 +1083,12 @@ int4mod(PG_FUNCTION_ARGS)
10831083
PG_RETURN_NULL();
10841084
}
10851085

1086-
/* SELECT ((-2147483648)::int4) % (-1); causes a floating point exception */
1087-
if (arg1 == INT_MIN && arg2 == -1)
1086+
/*
1087+
* Some machines throw a floating-point exception for INT_MIN % -1, which
1088+
* is a bit silly since the correct answer is perfectly well-defined,
1089+
* namely zero.
1090+
*/
1091+
if (arg2 == -1)
10881092
PG_RETURN_INT32(0);
10891093

10901094
/* No overflow is possible */
@@ -1107,6 +1111,15 @@ int2mod(PG_FUNCTION_ARGS)
11071111
PG_RETURN_NULL();
11081112
}
11091113

1114+
/*
1115+
* Some machines throw a floating-point exception for INT_MIN % -1, which
1116+
* is a bit silly since the correct answer is perfectly well-defined,
1117+
* namely zero. (It's not clear this ever happens when dealing with
1118+
* int16, but we might as well have the test for safety.)
1119+
*/
1120+
if (arg2 == -1)
1121+
PG_RETURN_INT16(0);
1122+
11101123
/* No overflow is possible */
11111124

11121125
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
@@ -657,6 +657,14 @@ int8mod(PG_FUNCTION_ARGS)
657657
PG_RETURN_NULL();
658658
}
659659

660+
/*
661+
* Some machines throw a floating-point exception for INT64_MIN % -1,
662+
* which is a bit silly since the correct answer is perfectly
663+
* well-defined, namely zero.
664+
*/
665+
if (arg2 == -1)
666+
PG_RETURN_INT64(0);
667+
660668
/* No overflow is possible */
661669

662670
PG_RETURN_INT64(arg1 % arg2);

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy