From 3b7171668528c82b464a7d2f523ef4564fc7045f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20L=C3=A9caille?= Date: Mon, 25 Feb 2019 15:04:22 +0100 Subject: [PATCH] MINOR: standard: Add a function to parse uints (dotted notation). This function is useful to parse strings made of unsigned integers and to allocate a C array of unsigned integers from there. For instance this function allocates this array { 1, 2, 3, 4, } from this string: "1.2.3.4". --- include/common/standard.h | 2 ++ src/standard.c | 44 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/include/common/standard.h b/include/common/standard.h index 4f4b2d509..6105eec2d 100644 --- a/include/common/standard.h +++ b/include/common/standard.h @@ -1367,6 +1367,8 @@ static inline void *my_realloc2(void *ptr, size_t size) return ret; } +int parse_dotted_uints(const char *s, unsigned int **nums, size_t *sz); + /* HAP_STRING() makes a string from a literal while HAP_XSTRING() first * evaluates the argument and is suited to pass macros. * diff --git a/src/standard.c b/src/standard.c index efa41710e..86dee4405 100644 --- a/src/standard.c +++ b/src/standard.c @@ -4058,6 +4058,50 @@ void debug_hexdump(FILE *out, const char *pfx, const char *buf, } } +/* + * Allocate an array of unsigned int with as address from string + * made of integer sepereated by dot characters. + * + * First, initializes the value with as address to 0 and initializes the + * array with as address to NULL. Then allocates the array with as + * address updating pointed value to the size of this array. + * + * Returns 1 if succeeded, 0 if not. + */ +int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz) +{ + unsigned int *n; + const char *s, *end; + + s = str; + *sz = 0; + end = str + strlen(str); + *nums = n = NULL; + + while (1) { + unsigned int r; + + if (s >= end) + break; + + r = read_uint(&s, end); + /* Expected characters after having read an uint: '\0' or '.', + * if '.', must not be terminal. + */ + if (*s != '\0'&& (*s++ != '.' || s == end)) + return 0; + + n = my_realloc2(n, *sz + 1); + if (!n) + return 0; + + n[(*sz)++] = r; + } + *nums = n; + + return 1; +} + /* do nothing, just a placeholder for debugging calls, the real one is in trace.c */ __attribute__((weak,format(printf, 1, 2))) void trace(char *msg, ...)