From 41c9caff1737e3e458f96fc2c3a6a1fd71cf3b31 Mon Sep 17 00:00:00 2001 From: Joachim Nilsson Date: Fri, 10 Jul 2015 18:58:55 +0200 Subject: [PATCH] Add atonum() - Convert string to natural number, returns -1 on error. Signed-off-by: Joachim Nilsson --- README.md | 5 +++++ lite.h | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/README.md b/README.md index 6835611..53b7e6c 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,11 @@ traversing lists while deleting/freeing nodes. Helper Macros ------------- +- `atonum(str)` + + Convert string to natural number, works for 32-bit non-negative + integers. Returns -1 on error. + - `blkdev(dev)` Create block device diff --git a/lite.h b/lite.h index 8541628..2e6aace 100644 --- a/lite.h +++ b/lite.h @@ -101,6 +101,20 @@ static inline int fisslashdir(char *dir) return 0; } +/* Convert string to natural number (0-2147483647), returns -1 on error. */ +static inline int atonum(const char *str) +{ + int val = -1; + char *errstr; + + if (str) { + val = strtonum(str, 0, INT32_MAX, &errstr); + if (errstr) + return -1; + } + + return val; +} /* Validate string, non NULL and not zero length */ static inline int string_valid (const char *s)