From 89eaad60065e35feb8517cf658534d1e38c20952 Mon Sep 17 00:00:00 2001 From: c9s Date: Thu, 15 May 2014 20:38:07 +0800 Subject: [PATCH] Add slug_to_pcre pattern function --- include/str.h | 3 +++ src/node.c | 7 +++++++ src/str.c | 24 ++++++++++++++++++++++++ tests/test_tree.c | 18 ++++++++++++++++++ 4 files changed, 52 insertions(+) diff --git a/include/str.h b/include/str.h index 46ec218..831d5c7 100644 --- a/include/str.h +++ b/include/str.h @@ -7,6 +7,8 @@ #ifndef STR_H #define STR_H +char * slug_to_pcre(char * slug, char sep); + char * ltrim_slash(char* str); char** str_split(char* a_str, const char a_delim); @@ -15,5 +17,6 @@ void str_repeat(char *s, char *c, int len); void print_indent(int level); + #endif /* !STR_H */ diff --git a/src/node.c b/src/node.c index d26b0ea..73b8212 100644 --- a/src/node.c +++ b/src/node.c @@ -103,6 +103,13 @@ redge * rnode_find_edge(rnode * n, char * pat) { return NULL; } +void rnode_combine_patterns(rnode * n) { + redge *e = NULL; + for ( int i = 0 ; i < n->children_len ; i++ ) { + e = n->children[i]; + } +} + rnode * rnode_lookup(rnode * tree, char * path, int path_len) { token_array * tokens = split_route_pattern(path, path_len); diff --git a/src/str.c b/src/str.c index 1585151..b707440 100644 --- a/src/str.c +++ b/src/str.c @@ -11,6 +11,30 @@ #include "str.h" #include "token.h" +/** + * @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; +} char * ltrim_slash(char* str) diff --git a/tests/test_tree.c b/tests/test_tree.c index fbb2e28..fa7a421 100644 --- a/tests/test_tree.c +++ b/tests/test_tree.c @@ -40,6 +40,23 @@ START_TEST (test_rnode_find_edge) END_TEST +START_TEST (test_slug_to_pcre) +{ + char * pattern; + pattern = slug_to_pcre("{id}", '/'); + fail_if( strcmp(pattern, "[^/]+") != 0 , "as [^/]+" ); + free(pattern); + + pattern = slug_to_pcre("{id:[a-z]+}", '/'); + fail_if( strcmp(pattern, "[a-z]+") != 0 , "as [a-z]+" ); + free(pattern); + + + +} +END_TEST + + START_TEST (test_rnode_insert_tokens) { token_array *t; @@ -152,6 +169,7 @@ Suite* r3_suite (void) { tcase_add_test(tcase, test_rnode_construct_uniq); tcase_add_test(tcase, test_rnode_find_edge); tcase_add_test(tcase, test_rnode_insert_tokens); + tcase_add_test(tcase, test_slug_to_pcre); suite_add_tcase(suite, tcase);