diff options
Diffstat (limited to 'common/stringhelp.c')
-rw-r--r-- | common/stringhelp.c | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/common/stringhelp.c b/common/stringhelp.c index ca8ae0bbc..6714eb8b9 100644 --- a/common/stringhelp.c +++ b/common/stringhelp.c @@ -48,6 +48,7 @@ # endif # include <windows.h> #endif +#include <assert.h> #include "util.h" #include "common-defs.h" @@ -1234,3 +1235,69 @@ strsplit (char *string, char delim, char replacement, int *count) return result; } + + +/* Tokenize STRING using the set of delimiters in DELIM. Leading + * spaces and tabs are removed from all tokens. The caller must xfree + * the result. + * + * Returns: A malloced and NULL delimited array with the tokens. On + * memory error NULL is returned and ERRNO is set. + */ +char ** +strtokenize (const char *string, const char *delim) +{ + const char *s; + size_t fields; + size_t bytes, n; + char *buffer; + char *p, *px, *pend; + char **result; + + /* Count the number of fields. */ + for (fields = 1, s = strpbrk (string, delim); s; s = strpbrk (s + 1, delim)) + fields++; + fields++; /* Add one for the terminating NULL. */ + + /* Allocate an array for all fields, a terminating NULL, and space + for a copy of the string. */ + bytes = fields * sizeof *result; + if (bytes / sizeof *result != fields) + { + gpg_err_set_errno (ENOMEM); + return NULL; + } + n = strlen (string) + 1; + bytes += n; + if (bytes < n) + { + gpg_err_set_errno (ENOMEM); + return NULL; + } + result = xtrymalloc (bytes); + if (!result) + return NULL; + buffer = (char*)(result + fields); + + /* Copy and parse the string. */ + strcpy (buffer, string); + for (n = 0, p = buffer; (pend = strpbrk (p, delim)); p = pend + 1) + { + *pend = 0; + while (spacep (p)) + p++; + for (px = pend - 1; px >= p && spacep (px); px--) + *px = 0; + result[n++] = p; + } + while (spacep (p)) + p++; + for (px = p + strlen (p) - 1; px >= p && spacep (px); px--) + *px = 0; + result[n++] = p; + result[n] = NULL; + + assert ((char*)(result + n + 1) == buffer); + + return result; +} |