diff mbox series

[v6,1/2] git-compat-util: add strtoi_with_tail()

Message ID 98e516a7be777f2697073e64b28c293e7a8a0011.1707025719.git.gitgitgadget@gmail.com (mailing list archive)
State New
Headers show
Series Replace atoi() with strtoi_with_tail() | expand

Commit Message

Mohit Marathe Feb. 4, 2024, 5:48 a.m. UTC
From: Mohit Marathe <mohitmarathe23@gmail.com>

This function is an updated version of strtol_i() function. It will
give more control to handle parsing of the characters after the
numbers and better error handling while parsing numbers.

Signed-off-by: Mohit Marathe <mohitmarathe@proton.me>
---
 git-compat-util.h | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)
diff mbox series

Patch

diff --git a/git-compat-util.h b/git-compat-util.h
index 7c2a6538e5a..59256a441de 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -1296,14 +1296,24 @@  static inline int strtoul_ui(char const *s, int base, unsigned int *result)
 	return 0;
 }
 
-static inline int strtol_i(char const *s, int base, int *result)
+#define strtol_i(s,b,r) strtoi_with_tail((s), (b), (r), NULL)
+static inline int strtoi_with_tail(char const *s, int base, int *result, char **endp)
 {
 	long ul;
-	char *p;
+	char *dummy = NULL;
 
+	if (!endp)
+		endp = &dummy;
 	errno = 0;
-	ul = strtol(s, &p, base);
-	if (errno || *p || p == s || (int) ul != ul)
+	ul = strtol(s, endp, base);
+	if (errno ||
+	    /*
+	     * if we are told to parse to the end of the string by
+	     * passing NULL to endp, it is an error to have any
+	     * remaining character after the digits.
+	     */
+	   (dummy && *dummy) ||
+	    *endp == s || (int) ul != ul)
 		return -1;
 	*result = ul;
 	return 0;