]> git.ipfire.org Git - thirdparty/haproxy.git/commitdiff
MINOR: standard: Add a function to parse uints (dotted notation).
authorFrédéric Lécaille <flecaille@haproxy.com>
Mon, 25 Feb 2019 14:04:22 +0000 (15:04 +0100)
committerWilly Tarreau <w@1wt.eu>
Tue, 26 Feb 2019 15:27:05 +0000 (16:27 +0100)
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
src/standard.c

index 4f4b2d509a98bbc2d0aea7b6fd12e5d2690d99cb..6105eec2df262358f748c3173001994ff2795227 100644 (file)
@@ -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.
  *
index efa41710e14e3723a795658f20b80be1852eea4d..86dee4405e6e8174be0b13ff1d05146602fe8a33 100644 (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 */
 __attribute__((weak,format(printf, 1, 2)))
 void trace(char *msg, ...)