Patchwork [v3] mtd-utils: new strtoX helpers

login
register
mail settings
Submitter Mike Frysinger
Date Sept. 27, 2010, 6:42 a.m.
Message ID <1285569748-16152-1-git-send-email-vapier@gentoo.org>
Download mbox | patch
Permalink /patch/65812/
State Accepted, archived
Headers show

Comments

Mike Frysinger - Sept. 27, 2010, 6:42 a.m.
Simply usage of converting strings to numbers by adding some wrappers
around the standard strtoX functions.  These helpers simplify the api
of these functions a bit by providing an optional "error" pointer and
automatic error message.

Signed-off-by: Mike Frysinger <vapier@gentoo.org>
---
v3
	- merge into common.h now that PROGRAM_NAME has been sorted out

 include/common.h |   24 ++++++++++++++++++++++++
 1 files changed, 24 insertions(+), 0 deletions(-)
Artem Bityutskiy - Sept. 27, 2010, 6:44 a.m.
On Mon, 2010-09-27 at 02:42 -0400, Mike Frysinger wrote:
> Simply usage of converting strings to numbers by adding some wrappers
> around the standard strtoX functions.  These helpers simplify the api
> of these functions a bit by providing an optional "error" pointer and
> automatic error message.
> 
> Signed-off-by: Mike Frysinger <vapier@gentoo.org>
> ---
> v3
> 	- merge into common.h now that PROGRAM_NAME has been sorted out

Pushed, thanks!

Patch

diff --git a/include/common.h b/include/common.h
index dce067b..472315e 100644
--- a/include/common.h
+++ b/include/common.h
@@ -20,6 +20,7 @@ 
 #define __MTD_UTILS_COMMON_H__
 
 #include <stdio.h>
+#include <stdlib.h>
 #include <ctype.h>
 #include <string.h>
 #include <errno.h>
@@ -79,6 +80,29 @@  static inline int is_power_of_2(unsigned long long n)
 	        return (n != 0 && ((n & (n - 1)) == 0));
 }
 
+/**
+ * simple_strtoX - convert a hex/dec/oct string into a number
+ * @snum: buffer to convert
+ * @error: set to 1 when buffer isn't fully consumed
+ */
+#define simple_strtoX(func, type) \
+static inline type simple_##func(const char *snum, int *error) \
+{ \
+	char *endptr; \
+	type ret = func(snum, &endptr, 0); \
+ \
+	if (error && (!*snum || *endptr)) { \
+		errmsg("%s: unable to parse the number '%s'", #func, snum); \
+		*error = 1; \
+	} \
+ \
+	return ret; \
+}
+simple_strtoX(strtol, long int)
+simple_strtoX(strtoll, long int)
+simple_strtoX(strtoul, unsigned long int)
+simple_strtoX(strtoull, unsigned long int)
+
 #ifdef __cplusplus
 }
 #endif