[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[PATCH 2/2] xstrtol: simplify integer overflow checking
From: |
Paul Eggert |
Subject: |
[PATCH 2/2] xstrtol: simplify integer overflow checking |
Date: |
Sun, 16 Jan 2022 22:48:30 -0800 |
* lib/xstrtol.c: Include intprops.h.
(TYPE_SIGNED): Remove, as intprops.h defines that for us now.
(bkm_scale): Use INT_MULTIPLY_WRAPV instead of checking for
overflow by hand.
---
ChangeLog | 6 ++++++
lib/xstrtol.c | 17 +++++++----------
2 files changed, 13 insertions(+), 10 deletions(-)
diff --git a/ChangeLog b/ChangeLog
index a1896fa7d3..2ea372b0e3 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,11 @@
2022-01-16 Paul Eggert <eggert@cs.ucla.edu>
+ xstrtol: simplify integer overflow checking
+ * lib/xstrtol.c: Include intprops.h.
+ (TYPE_SIGNED): Remove, as intprops.h defines that for us now.
+ (bkm_scale): Use INT_MULTIPLY_WRAPV instead of checking for
+ overflow by hand.
+
xstrtoll-tests: use %lld for long long
* tests/test-xstrtoll.c, tests/test-xstrtoull.c (__spec):
Do not assume long long is 64 bits, or that exact-width
diff --git a/lib/xstrtol.c b/lib/xstrtol.c
index c9776fb80c..6f5a8bef60 100644
--- a/lib/xstrtol.c
+++ b/lib/xstrtol.c
@@ -41,23 +41,20 @@
#include <string.h>
#include "assure.h"
-
-#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
+#include "intprops.h"
static strtol_error
bkm_scale (__strtol_t *x, int scale_factor)
{
- if (TYPE_SIGNED (__strtol_t) && *x < STRTOL_T_MINIMUM / scale_factor)
+ __strtol_t scaled;
+ if (INT_MULTIPLY_WRAPV (*x, scale_factor, &scaled))
{
- *x = STRTOL_T_MINIMUM;
+ *x = *x < 0 ? TYPE_MINIMUM (__strtol_t) : TYPE_MAXIMUM (__strtol_t);
return LONGINT_OVERFLOW;
}
- if (STRTOL_T_MAXIMUM / scale_factor < *x)
- {
- *x = STRTOL_T_MAXIMUM;
- return LONGINT_OVERFLOW;
- }
- *x *= scale_factor;
+ else
+ *x = scaled;
+
return LONGINT_OK;
}
--
2.32.0