| 1 |
#include <stdlib.h> |
| 2 |
#include <assert.h> |
| 3 |
|
| 4 |
#include "nstring.h" |
| 5 |
|
| 6 |
#include "token.h" |
| 7 |
|
| 8 |
|
| 9 |
void |
| 10 |
pm_gettoken(const char * const tokenStart, |
| 11 |
char const delimiter, |
| 12 |
const char ** const tokenP, |
| 13 |
const char ** const nextP, |
| 14 |
const char ** const errorP) { |
| 15 |
/*---------------------------------------------------------------------------- |
| 16 |
Find the token starting at 'tokenStart' up to but not including |
| 17 |
the first 'delimiter' character or end of string. Return it in newly |
| 18 |
malloced memory as *tokenP, NUL-terminated. |
| 19 |
|
| 20 |
Make *nextP point just past the token, i.e. to the delimiter or |
| 21 |
end of string NUL character. |
| 22 |
|
| 23 |
Note that if the string is empty, or starts with the delimiter, |
| 24 |
we return an empty string and *nextP == tokenStart, i.e. *nextP |
| 25 |
doesn't necessarily advance. |
| 26 |
-----------------------------------------------------------------------------*/ |
| 27 |
char * token; |
| 28 |
const char * cursor; |
| 29 |
unsigned int charCount; |
| 30 |
|
| 31 |
/* Run through the token, counting characters */ |
| 32 |
|
| 33 |
charCount = 0; /* initial value */ |
| 34 |
cursor = tokenStart; /* initial value */ |
| 35 |
*errorP = NULL; /* initial value */ |
| 36 |
|
| 37 |
while (*cursor != delimiter && *cursor != '\0' && !*errorP) { |
| 38 |
if (*cursor == '\\') { |
| 39 |
++cursor; |
| 40 |
if (*cursor == '\0') |
| 41 |
pm_asprintf(errorP, |
| 42 |
"string ends with an escape character (\\)"); |
| 43 |
} else { |
| 44 |
++cursor; |
| 45 |
++charCount; |
| 46 |
} |
| 47 |
} |
| 48 |
if (!*errorP) { |
| 49 |
token = malloc(charCount + 1); |
| 50 |
if (token == NULL) |
| 51 |
pm_asprintf(errorP, "Could not allocate %u bytes of memory " |
| 52 |
"to parse a string", |
| 53 |
charCount + 1); |
| 54 |
else { |
| 55 |
/* Go back and do it again, this time copying the characters */ |
| 56 |
charCount = 0; |
| 57 |
cursor = tokenStart; |
| 58 |
|
| 59 |
while (*cursor != delimiter && *cursor != '\0') { |
| 60 |
if (*cursor == '\\') |
| 61 |
++cursor; |
| 62 |
|
| 63 |
assert(*cursor != '\0'); |
| 64 |
|
| 65 |
token[charCount++] = *cursor++; |
| 66 |
} |
| 67 |
token[charCount] = '\0'; |
| 68 |
|
| 69 |
*tokenP = token; |
| 70 |
*nextP = cursor; |
| 71 |
} |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|