2014-05-14 22:08:42 -04:00
|
|
|
/*
|
|
|
|
* str.c
|
|
|
|
* Copyright (C) 2014 c9s <c9s@c9smba.local>
|
|
|
|
*
|
|
|
|
* Distributed under terms of the MIT license.
|
|
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <assert.h>
|
|
|
|
#include "str.h"
|
2014-05-15 00:47:14 -04:00
|
|
|
#include "token.h"
|
2014-05-14 22:08:42 -04:00
|
|
|
|
2014-05-15 08:38:07 -04:00
|
|
|
/**
|
|
|
|
* @param char * sep separator
|
|
|
|
*/
|
|
|
|
char * slug_to_pcre(char * slug, char sep)
|
|
|
|
{
|
|
|
|
char * p = NULL;
|
|
|
|
char * pat = NULL;
|
|
|
|
char * end = NULL;
|
|
|
|
|
|
|
|
if ( NULL != (p = strchr(slug, ':')) ) {
|
|
|
|
// this slug contains a pattern
|
|
|
|
end = strchr(p, '}');
|
|
|
|
|
|
|
|
// start after ':'
|
|
|
|
return strndup( (p + 1) , (end - p - 1) );
|
|
|
|
} else {
|
|
|
|
if ((pat = malloc(128)) == NULL) {
|
|
|
|
return (NULL);
|
|
|
|
}
|
|
|
|
// should return a '[^/]+' pattern
|
|
|
|
snprintf(pat, 128, "[^%c]+", sep);
|
|
|
|
}
|
|
|
|
return pat;
|
|
|
|
}
|
2014-05-14 22:08:42 -04:00
|
|
|
|
|
|
|
|
2014-05-15 00:53:48 -04:00
|
|
|
char * ltrim_slash(char* str)
|
|
|
|
{
|
|
|
|
char * p = str;
|
|
|
|
while (*p == '/') p++;
|
|
|
|
return strdup(p);
|
|
|
|
}
|
|
|
|
|
2014-05-14 22:08:42 -04:00
|
|
|
char** str_split(char* a_str, const char a_delim)
|
|
|
|
{
|
|
|
|
char** result = 0;
|
|
|
|
size_t count = 0;
|
|
|
|
char* tmp = a_str;
|
|
|
|
char* last_comma = 0;
|
|
|
|
char delim[2];
|
|
|
|
delim[0] = a_delim;
|
|
|
|
delim[1] = 0;
|
|
|
|
|
|
|
|
/* Count how many elements will be extracted. */
|
|
|
|
while (*tmp)
|
|
|
|
{
|
|
|
|
if (a_delim == *tmp)
|
|
|
|
{
|
|
|
|
count++;
|
|
|
|
last_comma = tmp;
|
|
|
|
}
|
|
|
|
tmp++;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Add space for trailing token. */
|
|
|
|
count += last_comma < (a_str + strlen(a_str) - 1);
|
|
|
|
|
|
|
|
/* Add space for terminating null string so caller
|
|
|
|
knows where the list of returned strings ends. */
|
|
|
|
count++;
|
|
|
|
|
|
|
|
result = malloc(sizeof(char*) * count);
|
|
|
|
|
|
|
|
if (result)
|
|
|
|
{
|
|
|
|
size_t idx = 0;
|
|
|
|
char* token = strtok(a_str, delim);
|
|
|
|
|
|
|
|
while (token)
|
|
|
|
{
|
|
|
|
assert(idx < count);
|
|
|
|
*(result + idx++) = strdup(token);
|
|
|
|
token = strtok(0, delim);
|
|
|
|
}
|
|
|
|
assert(idx == count - 1);
|
|
|
|
*(result + idx) = 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
2014-05-15 06:02:10 -04:00
|
|
|
|
|
|
|
void str_repeat(char *s, char *c, int len) {
|
|
|
|
while(len--) {
|
|
|
|
s[len - 1] = *c;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void print_indent(int level) {
|
|
|
|
int len = level * 2;
|
|
|
|
while(len--) {
|
|
|
|
printf(" ");
|
|
|
|
}
|
|
|
|
}
|