]> git.ozlabs.org Git - ccan/blobdiff - ccan/str_talloc/str_talloc.c
ccanlint: print coverage amount when -vv
[ccan] / ccan / str_talloc / str_talloc.c
index d1d2f44de4b875b994b4cd8e5899981a759bf44e..3bcb1f2a9cf3f7836603bfa9cbed7524f98c87ff 100644 (file)
@@ -4,10 +4,14 @@
 #include <limits.h>
 #include <stdlib.h>
 #include "str_talloc.h"
+#include <sys/types.h>
+#include <regex.h>
+#include <stdarg.h>
+#include <unistd.h>
 #include <ccan/talloc/talloc.h>
+#include <ccan/str/str.h>
 
-char **strsplit(const void *ctx, const char *string, const char *delims,
-                unsigned int *nump)
+char **strsplit(const void *ctx, const char *string, const char *delims)
 {
        char **lines = NULL;
        unsigned int max = 64, num = 0;
@@ -25,9 +29,9 @@ char **strsplit(const void *ctx, const char *string, const char *delims,
                        lines = talloc_realloc(ctx, lines, char *, max*=2 + 1);
        }
        lines[num] = NULL;
-       if (nump)
-               *nump = num;
-       return lines;
+
+       /* Shrink, so talloc_get_size works */
+       return talloc_realloc(ctx, lines, char *, num+1);
 }
 
 char *strjoin(const void *ctx, char *strings[], const char *delim)
@@ -41,3 +45,46 @@ char *strjoin(const void *ctx, char *strings[], const char *delim)
        }
        return ret;
 }
+
+bool strreg(const void *ctx, const char *string, const char *regex, ...)
+{
+       size_t nmatch = 1 + strcount(regex, "(");
+       regmatch_t *matches = talloc_array(ctx, regmatch_t, nmatch);
+       regex_t r;
+       bool ret;
+
+       if (!matches || regcomp(&r, regex, REG_EXTENDED) != 0)
+               return false;
+
+       if (regexec(&r, string, nmatch, matches, 0) == 0) {
+               unsigned int i;
+               va_list ap;
+
+               ret = true;
+               va_start(ap, regex);
+               for (i = 1; i < nmatch; i++) {
+                       char **arg;
+                       arg = va_arg(ap, char **);
+                       if (arg) {
+                               /* eg. ([a-z])? can give "no match". */
+                               if (matches[i].rm_so == -1)
+                                       *arg = NULL;
+                               else {
+                                       *arg = talloc_strndup(ctx,
+                                                     string + matches[i].rm_so,
+                                                     matches[i].rm_eo
+                                                     - matches[i].rm_so);
+                                       if (!*arg) {
+                                               ret = false;
+                                               break;
+                                       }
+                               }
+                       }
+               }
+               va_end(ap);
+       } else
+               ret = false;
+       talloc_free(matches);
+       regfree(&r);
+       return ret;
+}