BLI_string: Adding the BLI_strtok_r function, which mimics stdlib strtok_r (unavailable on some systems).

It allows to iterate over a string, returning an new element each time, using a char as separator. See BLI_String.h's comments for more info and an example.

Needed by the UI template list patch following!
This commit is contained in:
Bastien Montagne
2011-10-28 13:07:11 +00:00
parent 0d63bb005f
commit 2ed7a66653
2 changed files with 51 additions and 0 deletions

View File

@@ -133,6 +133,28 @@ int BLI_strncasecmp(const char *s1, const char *s2, size_t len);
int BLI_natstrcmp(const char *s1, const char *s2); int BLI_natstrcmp(const char *s1, const char *s2);
size_t BLI_strnlen(const char *str, size_t maxlen); size_t BLI_strnlen(const char *str, size_t maxlen);
/**
* Split str on the first occurence of delimiter, returns the first
* part as a mallocN'd string, and stores the second part into
* ctx (also mallocN'd).
* If str is NULL, split on ctx instead.
* This allows to iterate over this "generator" function:
*
* char *ctx = NULL;
* char *res = NULL;
* for(res = BLI_strtok_r("a;dummy;csv;line", ";", &ctx); res; res = BLI_strtok_r(NULL, ";", &ctx)) {
* printf(res);
* MEM_freeN(res);
* }
*
* @param str The string to be split.
* @param delimiter The char used to split str apart.
* @param ctx The "context" string. Its a pointer inside the org passed @str,
* so it has no specific mem management.
* @retval Returns the mallocN'd first element from split str (or ctx).
*/
char *BLI_strtok_r(char *str, const char *delimiter, char **ctx);
void BLI_timestr(double _time, char *str); /* time var is global */ void BLI_timestr(double _time, char *str); /* time var is global */
void BLI_ascii_strtolower(char *str, int len); void BLI_ascii_strtolower(char *str, int len);

View File

@@ -375,6 +375,35 @@ int BLI_natstrcmp(const char *s1, const char *s2)
return 0; return 0;
} }
/* As unfortunately strtok_r is not available everywhere... */
char *BLI_strtok_r(char *str, const char *delimiter, char **ctx)
{
char *cut = NULL, *ret = NULL;
char *split = str ? str : *ctx;
if(!split) {
return ret;
}
cut = strchr(split, *delimiter);
if(cut) {
size_t len_ret = cut - split;
size_t len_ctx = strlen(split) - len_ret - 1;
ret = BLI_strdupn(split, len_ret);
if(len_ctx > 0) {
*ctx = split+len_ret+1;
}
else {
*ctx = NULL;
}
}
else {
ret = BLI_strdup(split);
*ctx = NULL;
}
return ret;
}
void BLI_timestr(double _time, char *str) void BLI_timestr(double _time, char *str)
{ {
/* format 00:00:00.00 (hr:min:sec) string has to be 12 long */ /* format 00:00:00.00 (hr:min:sec) string has to be 12 long */