Message ID | 60ea85a701a05831b0adf1e3f9a7a97fd31ef43f.1706079304.git.gitgitgadget@gmail.com (mailing list archive) |
---|---|
State | New, archived |
Headers | show |
Series | Replace atoi() with strtol_i_updated() | expand |
"Mohit Marathe via GitGitGadget" <gitgitgadget@gmail.com> writes: > 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 > integer and better error handling while parsing numbers. i2 was horrible but this is worse. What would you call an even newer variant when you need to add one? strtol_i_updated_twice? To readers who are reading the code in 6 months, it is totally uninteresting that strtol_i() is an older function and the new thing was invented later as its update. What they want to learn is how these two are different, what additional things this new one lets them do compared to the old one, namely: we can optionally learn where the run of the digits has ended. Perhaps call it "strtoi_with_tail" or something, unless others suggest even better names? Thanks.
diff --git a/git-compat-util.h b/git-compat-util.h index 7c2a6538e5a..b38d7c7f8f1 100644 --- a/git-compat-util.h +++ b/git-compat-util.h @@ -1309,6 +1309,29 @@ static inline int strtol_i(char const *s, int base, int *result) return 0; } +#define strtol_i(s,b,r) strtol_i_updated((s), (b), (r), NULL) +static inline int strtol_i_updated(char const *s, int base, int *result, char **endp) +{ + long ul; + char *dummy = NULL; + + if (!endp) + endp = &dummy; + errno = 0; + 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; +} + void git_stable_qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *)); #ifdef INTERNAL_QSORT