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".
This commit is contained in:
Frdric Lcaille 2019-02-25 15:04:22 +01:00 committed by Willy Tarreau
parent 0bbad6bb06
commit 3b71716685
2 changed files with 46 additions and 0 deletions

View File

@ -1367,6 +1367,8 @@ static inline void *my_realloc2(void *ptr, size_t size)
return ret; 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 /* HAP_STRING() makes a string from a literal while HAP_XSTRING() first
* evaluates the argument and is suited to pass macros. * evaluates the argument and is suited to pass macros.
* *

View File

@ -4058,6 +4058,50 @@ void debug_hexdump(FILE *out, const char *pfx, const char *buf,
} }
} }
/*
* Allocate an array of unsigned int with <nums> as address from <str> string
* made of integer sepereated by dot characters.
*
* First, initializes the value with <sz> as address to 0 and initializes the
* array with <nums> as address to NULL. Then allocates the array with <nums> as
* address updating <sz> 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 */ /* do nothing, just a placeholder for debugging calls, the real one is in trace.c */
__attribute__((weak,format(printf, 1, 2))) __attribute__((weak,format(printf, 1, 2)))
void trace(char *msg, ...) void trace(char *msg, ...)