diff mbox series

[v9,1/8] git-compat-util: add strtoul_ul() with error handling

Message ID 20250108183740.67022-2-eric.peijian@gmail.com (mailing list archive)
State Superseded
Headers show
Series cat-file: add remote-object-info to batch-command | expand

Commit Message

Eric Ju Jan. 8, 2025, 6:37 p.m. UTC
We already have strtoul_ui() and similar functions that provide proper
error handling using strtoul from the standard library. However,
there isn't currently a variant that returns an unsigned long.
This commit introduces strtoul_ul() to address this gap, enabling the
return of an unsigned long with proper error handling.
---
 git-compat-util.h | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

Comments

Christian Couder Jan. 10, 2025, 11:33 a.m. UTC | #1
On Wed, Jan 8, 2025 at 7:38 PM Eric Ju <eric.peijian@gmail.com> wrote:

> +// Converts a string to an unsigned long using the standard library's strtoul,
> +// with additional error handling to ensure robustness.

We use comments like this:

/*
 * Converts a string to an unsigned long using the standard library's strtoul,
 * with additional error handling to ensure robustness.
 */

Also we use the imperative mood in comments before a function, so:

s/Converts/Convert/
Eric Ju Jan. 14, 2025, 1:39 a.m. UTC | #2
Thank you. Fixed in v10.

On Fri, Jan 10, 2025 at 6:33 AM Christian Couder
<christian.couder@gmail.com> wrote:
>
> On Wed, Jan 8, 2025 at 7:38 PM Eric Ju <eric.peijian@gmail.com> wrote:
>
> > +// Converts a string to an unsigned long using the standard library's strtoul,
> > +// with additional error handling to ensure robustness.
>
> We use comments like this:
>
> /*
>  * Converts a string to an unsigned long using the standard library's strtoul,
>  * with additional error handling to ensure robustness.
>  */
>
> Also we use the imperative mood in comments before a function, so:
>
> s/Converts/Convert/
diff mbox series

Patch

diff --git a/git-compat-util.h b/git-compat-util.h
index e283c46c6f..3bdb085624 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -1351,6 +1351,24 @@  static inline int strtoul_ui(char const *s, int base, unsigned int *result)
 	return 0;
 }
 
+// Converts a string to an unsigned long using the standard library's strtoul,
+// with additional error handling to ensure robustness.
+static inline int strtoul_ul(char const *s, int base, unsigned long *result)
+{
+	unsigned long ul;
+	char *p;
+
+	errno = 0;
+	/* negative values would be accepted by strtoul */
+	if (strchr(s, '-'))
+		return -1;
+	ul = strtoul(s, &p, base);
+	if (errno || *p || p == s )
+		return -1;
+	*result = ul;
+	return 0;
+}
+
 static inline int strtol_i(char const *s, int base, int *result)
 {
 	long ul;