From 71cf5a598192fd1bbc715cb90498011a609a78cf Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Thu, 22 Feb 2024 11:42:56 +0100 Subject: [PATCH 01/21] feat: initial trie routing structure --- include/lnm/common.h | 2 + src/_include/lnm/http/router_internal.h | 36 ++++++++++++ src/http/lnm_http_router.c | 73 +++++++++++++++++++++++++ 3 files changed, 111 insertions(+) create mode 100644 src/_include/lnm/http/router_internal.h create mode 100644 src/http/lnm_http_router.c diff --git a/include/lnm/common.h b/include/lnm/common.h index 8cc982e..3ada2a4 100644 --- a/include/lnm/common.h +++ b/include/lnm/common.h @@ -32,6 +32,8 @@ typedef enum lnm_err { lnm_err_not_setup, lnm_err_bad_regex, lnm_err_not_found, + lnm_err_invalid_route, + lnm_err_overlapping_route, } lnm_err; typedef struct lnm_loop lnm_http_loop; diff --git a/src/_include/lnm/http/router_internal.h b/src/_include/lnm/http/router_internal.h new file mode 100644 index 0000000..e4f6bda --- /dev/null +++ b/src/_include/lnm/http/router_internal.h @@ -0,0 +1,36 @@ +#ifndef LNM_HTTP_ROUTER_INTERNAL +#define LNM_HTTP_ROUTER_INTERNAL + +#include "lnm/common.h" + +typedef struct lnm_http_route { +} lnm_http_route; + +typedef struct lnm_http_router { + struct lnm_http_router *exact_children[128]; + struct lnm_http_router *single_segment_child; + lnm_http_route *route; +} lnm_http_router; + +/** + * Allocate and initialize a new http_router. + */ +lnm_err lnm_http_router_init(lnm_http_router **out); + +void lnm_http_router_free(lnm_http_router *router); + +lnm_err lnm_http_route_init(lnm_http_route **out); + +void lnm_http_route_free(lnm_http_route *route); + +lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, + const char *path); + +/** + * Add all of the child router's routes to the parent router, under the given + * route prefix. + */ +lnm_err lnm_http_router_nest(lnm_http_router *parent, + const lnm_http_router *child, const char *prefix); + +#endif diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c new file mode 100644 index 0000000..f5001f8 --- /dev/null +++ b/src/http/lnm_http_router.c @@ -0,0 +1,73 @@ +#include + +#include "lnm/common.h" +#include "lnm/http/router_internal.h" + +lnm_err lnm_http_router_init(lnm_http_router **out) { + lnm_http_router *router = calloc(1, sizeof(lnm_http_router)); + + if (router == NULL) { + return lnm_err_failed_alloc; + } + + *out = router; + + return lnm_err_ok; +} + +lnm_err lnm_http_route_init(lnm_http_route **out) { + lnm_http_route *route = calloc(1, sizeof(lnm_http_route)); + + if (route == NULL) { + return lnm_err_failed_alloc; + } + + *out = route; + + return lnm_err_ok; +} + +static bool is_ascii(const char *s) { + while (*s != '0') { + if (*s > 127) { + return false; + } + + s++; + } + + return true; +} + +lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, + const char *path) { + if (path[0] != '/' || !is_ascii(path)) { + return lnm_err_invalid_route; + } + + while (*path != '\0') { + unsigned char c = *path; + + switch (c) { + case ':': + LNM_RES(lnm_http_router_init(&http_router->single_segment_child)); + + // All other characters in the segment are ignored + const char *next_slash_ptr = strchr(path, '/'); + path = next_slash_ptr == NULL ? strchr(path, '\0') : next_slash_ptr; + break; + case '*': + // TODO multi-segment wildcard + break; + default: + LNM_RES(lnm_http_router_init(&http_router->exact_children[c])); + http_router = http_router->exact_children[c]; + path++; + break; + } + } + + LNM_RES(lnm_http_route_init(out)); + + return lnm_err_ok; +} From 0e1d5d3f23a59e46ce94e2cf9eeb1da4bfe678b6 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Thu, 22 Feb 2024 17:43:30 +0100 Subject: [PATCH 02/21] chore: add test folder --- Makefile | 2 +- test/routing.c | 5 + test/test.h | 1839 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 1845 insertions(+), 1 deletion(-) create mode 100644 test/routing.c create mode 100644 test/test.h diff --git a/Makefile b/Makefile index 5fb194f..e52bb1f 100644 --- a/Makefile +++ b/Makefile @@ -73,7 +73,7 @@ $(BINS_TEST): %: %.c.o $(LIB) $(BUILD_DIR)/$(TEST_DIR)/%.c.o: $(TEST_DIR)/%.c mkdir -p $(dir $@) $(CC) $(_CFLAGS) -I$(TEST_DIR) \ - -I$(dir $(@:$(BUILD_DIR)/$(TEST_DIR)/%=$(SRC_DIR)/%)) \ + -I$(SRC_DIR)/_include \ -c $< -o $@ # =====EXAMPLES===== diff --git a/test/routing.c b/test/routing.c new file mode 100644 index 0000000..acab1cc --- /dev/null +++ b/test/routing.c @@ -0,0 +1,5 @@ +#include "test.h" + +TEST_LIST = { + { NULL, NULL } +}; diff --git a/test/test.h b/test/test.h new file mode 100644 index 0000000..9ab8f88 --- /dev/null +++ b/test/test.h @@ -0,0 +1,1839 @@ +/* + * Acutest -- Another C/C++ Unit Test facility + * + * + * Copyright 2013-2020 Martin Mitas + * Copyright 2019 Garrett D'Amore + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#ifndef ACUTEST_H +#define ACUTEST_H + + +/************************ + *** Public interface *** + ************************/ + +/* By default, "acutest.h" provides the main program entry point (function + * main()). However, if the test suite is composed of multiple source files + * which include "acutest.h", then this causes a problem of multiple main() + * definitions. To avoid this problem, #define macro TEST_NO_MAIN in all + * compilation units but one. + */ + +/* Macro to specify list of unit tests in the suite. + * The unit test implementation MUST provide list of unit tests it implements + * with this macro: + * + * TEST_LIST = { + * { "test1_name", test1_func_ptr }, + * { "test2_name", test2_func_ptr }, + * ... + * { NULL, NULL } // zeroed record marking the end of the list + * }; + * + * The list specifies names of each test (must be unique) and pointer to + * a function implementing it. The function does not take any arguments + * and has no return values, i.e. every test function has to be compatible + * with this prototype: + * + * void test_func(void); + * + * Note the list has to be ended with a zeroed record. + */ +#define TEST_LIST const struct acutest_test_ acutest_list_[] + + +/* Macros for testing whether an unit test succeeds or fails. These macros + * can be used arbitrarily in functions implementing the unit tests. + * + * If any condition fails throughout execution of a test, the test fails. + * + * TEST_CHECK takes only one argument (the condition), TEST_CHECK_ allows + * also to specify an error message to print out if the condition fails. + * (It expects printf-like format string and its parameters). The macros + * return non-zero (condition passes) or 0 (condition fails). + * + * That can be useful when more conditions should be checked only if some + * preceding condition passes, as illustrated in this code snippet: + * + * SomeStruct* ptr = allocate_some_struct(); + * if(TEST_CHECK(ptr != NULL)) { + * TEST_CHECK(ptr->member1 < 100); + * TEST_CHECK(ptr->member2 > 200); + * } + */ +#define TEST_CHECK_(cond,...) acutest_check_((cond), __FILE__, __LINE__, __VA_ARGS__) +#define TEST_CHECK(cond) acutest_check_((cond), __FILE__, __LINE__, "%s", #cond) + + +/* These macros are the same as TEST_CHECK_ and TEST_CHECK except that if the + * condition fails, the currently executed unit test is immediately aborted. + * + * That is done either by calling abort() if the unit test is executed as a + * child process; or via longjmp() if the unit test is executed within the + * main Acutest process. + * + * As a side effect of such abortion, your unit tests may cause memory leaks, + * unflushed file descriptors, and other phenomena caused by the abortion. + * + * Therefore you should not use these as a general replacement for TEST_CHECK. + * Use it with some caution, especially if your test causes some other side + * effects to the outside world (e.g. communicating with some server, inserting + * into a database etc.). + */ +#define TEST_ASSERT_(cond,...) \ + do { \ + if(!acutest_check_((cond), __FILE__, __LINE__, __VA_ARGS__)) \ + acutest_abort_(); \ + } while(0) +#define TEST_ASSERT(cond) \ + do { \ + if(!acutest_check_((cond), __FILE__, __LINE__, "%s", #cond)) \ + acutest_abort_(); \ + } while(0) + + +#ifdef __cplusplus +/* Macros to verify that the code (the 1st argument) throws exception of given + * type (the 2nd argument). (Note these macros are only available in C++.) + * + * TEST_EXCEPTION_ is like TEST_EXCEPTION but accepts custom printf-like + * message. + * + * For example: + * + * TEST_EXCEPTION(function_that_throw(), ExpectedExceptionType); + * + * If the function_that_throw() throws ExpectedExceptionType, the check passes. + * If the function throws anything incompatible with ExpectedExceptionType + * (or if it does not thrown an exception at all), the check fails. + */ +#define TEST_EXCEPTION(code, exctype) \ + do { \ + bool exc_ok_ = false; \ + const char *msg_ = NULL; \ + try { \ + code; \ + msg_ = "No exception thrown."; \ + } catch(exctype const&) { \ + exc_ok_= true; \ + } catch(...) { \ + msg_ = "Unexpected exception thrown."; \ + } \ + acutest_check_(exc_ok_, __FILE__, __LINE__, #code " throws " #exctype);\ + if(msg_ != NULL) \ + acutest_message_("%s", msg_); \ + } while(0) +#define TEST_EXCEPTION_(code, exctype, ...) \ + do { \ + bool exc_ok_ = false; \ + const char *msg_ = NULL; \ + try { \ + code; \ + msg_ = "No exception thrown."; \ + } catch(exctype const&) { \ + exc_ok_= true; \ + } catch(...) { \ + msg_ = "Unexpected exception thrown."; \ + } \ + acutest_check_(exc_ok_, __FILE__, __LINE__, __VA_ARGS__); \ + if(msg_ != NULL) \ + acutest_message_("%s", msg_); \ + } while(0) +#endif /* #ifdef __cplusplus */ + + +/* Sometimes it is useful to split execution of more complex unit tests to some + * smaller parts and associate those parts with some names. + * + * This is especially handy if the given unit test is implemented as a loop + * over some vector of multiple testing inputs. Using these macros allow to use + * sort of subtitle for each iteration of the loop (e.g. outputting the input + * itself or a name associated to it), so that if any TEST_CHECK condition + * fails in the loop, it can be easily seen which iteration triggers the + * failure, without the need to manually output the iteration-specific data in + * every single TEST_CHECK inside the loop body. + * + * TEST_CASE allows to specify only single string as the name of the case, + * TEST_CASE_ provides all the power of printf-like string formatting. + * + * Note that the test cases cannot be nested. Starting a new test case ends + * implicitly the previous one. To end the test case explicitly (e.g. to end + * the last test case after exiting the loop), you may use TEST_CASE(NULL). + */ +#define TEST_CASE_(...) acutest_case_(__VA_ARGS__) +#define TEST_CASE(name) acutest_case_("%s", name) + + +/* Maximal output per TEST_CASE call. Longer messages are cut. + * You may define another limit prior including "acutest.h" + */ +#ifndef TEST_CASE_MAXSIZE +#define TEST_CASE_MAXSIZE 64 +#endif + + +/* printf-like macro for outputting an extra information about a failure. + * + * Intended use is to output some computed output versus the expected value, + * e.g. like this: + * + * if(!TEST_CHECK(produced == expected)) { + * TEST_MSG("Expected: %d", expected); + * TEST_MSG("Produced: %d", produced); + * } + * + * Note the message is only written down if the most recent use of any checking + * macro (like e.g. TEST_CHECK or TEST_EXCEPTION) in the current test failed. + * This means the above is equivalent to just this: + * + * TEST_CHECK(produced == expected); + * TEST_MSG("Expected: %d", expected); + * TEST_MSG("Produced: %d", produced); + * + * The macro can deal with multi-line output fairly well. It also automatically + * adds a final new-line if there is none present. + */ +#define TEST_MSG(...) acutest_message_(__VA_ARGS__) + + +/* Maximal output per TEST_MSG call. Longer messages are cut. + * You may define another limit prior including "acutest.h" + */ +#ifndef TEST_MSG_MAXSIZE +#define TEST_MSG_MAXSIZE 1024 +#endif + + +/* Macro for dumping a block of memory. + * + * Its intended use is very similar to what TEST_MSG is for, but instead of + * generating any printf-like message, this is for dumping raw block of a + * memory in a hexadecimal form: + * + * TEST_CHECK(size_produced == size_expected && + * memcmp(addr_produced, addr_expected, size_produced) == 0); + * TEST_DUMP("Expected:", addr_expected, size_expected); + * TEST_DUMP("Produced:", addr_produced, size_produced); + */ +#define TEST_DUMP(title, addr, size) acutest_dump_(title, addr, size) + +/* Maximal output per TEST_DUMP call (in bytes to dump). Longer blocks are cut. + * You may define another limit prior including "acutest.h" + */ +#ifndef TEST_DUMP_MAXSIZE +#define TEST_DUMP_MAXSIZE 1024 +#endif + + +/* Common test initialiation/clean-up + * + * In some test suites, it may be needed to perform some sort of the same + * initialization and/or clean-up in all the tests. + * + * Such test suites may use macros TEST_INIT and/or TEST_FINI prior including + * this header. The expansion of the macro is then used as a body of helper + * function called just before executing every single (TEST_INIT) or just after + * it ends (TEST_FINI). + * + * Examples of various ways how to use the macro TEST_INIT: + * + * #define TEST_INIT my_init_func(); + * #define TEST_INIT my_init_func() // Works even without the semicolon + * #define TEST_INIT setlocale(LC_ALL, NULL); + * #define TEST_INIT { setlocale(LC_ALL, NULL); my_init_func(); } + * + * TEST_FINI is to be used in the same way. + */ + + +/********************** + *** Implementation *** + **********************/ + +/* The unit test files should not rely on anything below. */ + +#include +#include +#include +#include +#include +#include + +#if defined(unix) || defined(__unix__) || defined(__unix) || defined(__APPLE__) +#define ACUTEST_UNIX_ 1 +#include +#include +#include +#include +#include +#include +#include + +#if defined CLOCK_PROCESS_CPUTIME_ID && defined CLOCK_MONOTONIC +#define ACUTEST_HAS_POSIX_TIMER_ 1 +#endif +#endif + +#if defined(_gnu_linux_) || defined(__linux__) +#define ACUTEST_LINUX_ 1 +#include +#include +#endif + +#if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__) +#define ACUTEST_WIN_ 1 + #include + #include +#endif + +#if defined(__APPLE__) +#define ACUTEST_MACOS_ + #include + #include + #include + #include + #include +#endif + +#ifdef __cplusplus +#include +#endif + +#ifdef __has_include +#if __has_include() +#include +#endif +#endif + +/* Enable the use of the non-standard keyword __attribute__ to silence warnings under some compilers */ +#if defined(__GNUC__) || defined(__clang__) +#define ACUTEST_ATTRIBUTE_(attr) __attribute__((attr)) +#else +#define ACUTEST_ATTRIBUTE_(attr) +#endif + +/* Note our global private identifiers end with '_' to mitigate risk of clash + * with the unit tests implementation. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef _MSC_VER +/* In the multi-platform code like ours, we cannot use the non-standard + * "safe" functions from Microsoft C lib like e.g. sprintf_s() instead of + * standard sprintf(). Hence, lets disable the warning C4996. */ + #pragma warning(push) + #pragma warning(disable: 4996) +#endif + + +struct acutest_test_ { + const char* name; + void (*func)(void); +}; + +struct acutest_test_data_ { + unsigned char flags; + double duration; +}; + +enum { + ACUTEST_FLAG_RUN_ = 1 << 0, + ACUTEST_FLAG_SUCCESS_ = 1 << 1, + ACUTEST_FLAG_FAILURE_ = 1 << 2, +}; + +extern const struct acutest_test_ acutest_list_[]; + +int acutest_check_(int cond, const char* file, int line, const char* fmt, ...); +void acutest_case_(const char* fmt, ...); +void acutest_message_(const char* fmt, ...); +void acutest_dump_(const char* title, const void* addr, size_t size); +void acutest_abort_(void) ACUTEST_ATTRIBUTE_(noreturn); + + +#ifndef TEST_NO_MAIN + +static char* acutest_argv0_ = NULL; +static size_t acutest_list_size_ = 0; +static struct acutest_test_data_* acutest_test_data_ = NULL; +static size_t acutest_count_ = 0; +static int acutest_no_exec_ = -1; +static int acutest_no_summary_ = 0; +static int acutest_tap_ = 0; +static int acutest_skip_mode_ = 0; +static int acutest_worker_ = 0; +static int acutest_worker_index_ = 0; +static int acutest_cond_failed_ = 0; +static int acutest_was_aborted_ = 0; +static FILE *acutest_xml_output_ = NULL; + +static int acutest_stat_failed_units_ = 0; +static int acutest_stat_run_units_ = 0; + +static const struct acutest_test_* acutest_current_test_ = NULL; +static int acutest_current_index_ = 0; +static char acutest_case_name_[TEST_CASE_MAXSIZE] = ""; +static int acutest_test_already_logged_ = 0; +static int acutest_case_already_logged_ = 0; +static int acutest_verbose_level_ = 2; +static int acutest_test_failures_ = 0; +static int acutest_colorize_ = 0; +static int acutest_timer_ = 0; + +static int acutest_abort_has_jmp_buf_ = 0; +static jmp_buf acutest_abort_jmp_buf_; + + +static void +acutest_cleanup_(void) +{ + free((void*) acutest_test_data_); +} + +static void ACUTEST_ATTRIBUTE_(noreturn) +acutest_exit_(int exit_code) +{ + acutest_cleanup_(); + exit(exit_code); +} + +#if defined ACUTEST_WIN_ +typedef LARGE_INTEGER acutest_timer_type_; + static LARGE_INTEGER acutest_timer_freq_; + static acutest_timer_type_ acutest_timer_start_; + static acutest_timer_type_ acutest_timer_end_; + + static void + acutest_timer_init_(void) + { + QueryPerformanceFrequency(´st_timer_freq_); + } + + static void + acutest_timer_get_time_(LARGE_INTEGER* ts) + { + QueryPerformanceCounter(ts); + } + + static double + acutest_timer_diff_(LARGE_INTEGER start, LARGE_INTEGER end) + { + double duration = (double)(end.QuadPart - start.QuadPart); + duration /= (double)acutest_timer_freq_.QuadPart; + return duration; + } + + static void + acutest_timer_print_diff_(void) + { + printf("%.6lf secs", acutest_timer_diff_(acutest_timer_start_, acutest_timer_end_)); + } +#elif defined ACUTEST_HAS_POSIX_TIMER_ +static clockid_t acutest_timer_id_; +typedef struct timespec acutest_timer_type_; +static acutest_timer_type_ acutest_timer_start_; +static acutest_timer_type_ acutest_timer_end_; + +static void +acutest_timer_init_(void) +{ + if(acutest_timer_ == 1) + acutest_timer_id_ = CLOCK_MONOTONIC; + else if(acutest_timer_ == 2) + acutest_timer_id_ = CLOCK_PROCESS_CPUTIME_ID; +} + +static void +acutest_timer_get_time_(struct timespec* ts) +{ + clock_gettime(acutest_timer_id_, ts); +} + +static double +acutest_timer_diff_(struct timespec start, struct timespec end) +{ + double endns; + double startns; + + endns = end.tv_sec; + endns *= 1e9; + endns += end.tv_nsec; + + startns = start.tv_sec; + startns *= 1e9; + startns += start.tv_nsec; + + return ((endns - startns)/ 1e9); +} + +static void +acutest_timer_print_diff_(void) +{ + printf("%.6lf secs", + acutest_timer_diff_(acutest_timer_start_, acutest_timer_end_)); +} +#else +typedef int acutest_timer_type_; + static acutest_timer_type_ acutest_timer_start_; + static acutest_timer_type_ acutest_timer_end_; + + void + acutest_timer_init_(void) + {} + + static void + acutest_timer_get_time_(int* ts) + { + (void) ts; + } + + static double + acutest_timer_diff_(int start, int end) + { + (void) start; + (void) end; + return 0.0; + } + + static void + acutest_timer_print_diff_(void) + {} +#endif + +#define ACUTEST_COLOR_DEFAULT_ 0 +#define ACUTEST_COLOR_GREEN_ 1 +#define ACUTEST_COLOR_RED_ 2 +#define ACUTEST_COLOR_DEFAULT_INTENSIVE_ 3 +#define ACUTEST_COLOR_GREEN_INTENSIVE_ 4 +#define ACUTEST_COLOR_RED_INTENSIVE_ 5 + +static int ACUTEST_ATTRIBUTE_(format (printf, 2, 3)) +acutest_colored_printf_(int color, const char* fmt, ...) +{ + va_list args; + char buffer[256]; + int n; + + va_start(args, fmt); + vsnprintf(buffer, sizeof(buffer), fmt, args); + va_end(args); + buffer[sizeof(buffer)-1] = '\0'; + + if(!acutest_colorize_) { + return printf("%s", buffer); + } + +#if defined ACUTEST_UNIX_ + { + const char* col_str; + switch(color) { + case ACUTEST_COLOR_GREEN_: col_str = "\033[0;32m"; break; + case ACUTEST_COLOR_RED_: col_str = "\033[0;31m"; break; + case ACUTEST_COLOR_GREEN_INTENSIVE_: col_str = "\033[1;32m"; break; + case ACUTEST_COLOR_RED_INTENSIVE_: col_str = "\033[1;31m"; break; + case ACUTEST_COLOR_DEFAULT_INTENSIVE_: col_str = "\033[1m"; break; + default: col_str = "\033[0m"; break; + } + printf("%s", col_str); + n = printf("%s", buffer); + printf("\033[0m"); + return n; + } +#elif defined ACUTEST_WIN_ + { + HANDLE h; + CONSOLE_SCREEN_BUFFER_INFO info; + WORD attr; + + h = GetStdHandle(STD_OUTPUT_HANDLE); + GetConsoleScreenBufferInfo(h, &info); + + switch(color) { + case ACUTEST_COLOR_GREEN_: attr = FOREGROUND_GREEN; break; + case ACUTEST_COLOR_RED_: attr = FOREGROUND_RED; break; + case ACUTEST_COLOR_GREEN_INTENSIVE_: attr = FOREGROUND_GREEN | FOREGROUND_INTENSITY; break; + case ACUTEST_COLOR_RED_INTENSIVE_: attr = FOREGROUND_RED | FOREGROUND_INTENSITY; break; + case ACUTEST_COLOR_DEFAULT_INTENSIVE_: attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY; break; + default: attr = 0; break; + } + if(attr != 0) + SetConsoleTextAttribute(h, attr); + n = printf("%s", buffer); + SetConsoleTextAttribute(h, info.wAttributes); + return n; + } +#else + n = printf("%s", buffer); + return n; +#endif +} + +static void +acutest_begin_test_line_(const struct acutest_test_* test) +{ + if(!acutest_tap_) { + if(acutest_verbose_level_ >= 3) { + acutest_colored_printf_(ACUTEST_COLOR_DEFAULT_INTENSIVE_, "Test %s:\n", test->name); + acutest_test_already_logged_++; + } else if(acutest_verbose_level_ >= 1) { + int n; + char spaces[48]; + + n = acutest_colored_printf_(ACUTEST_COLOR_DEFAULT_INTENSIVE_, "Test %s... ", test->name); + memset(spaces, ' ', sizeof(spaces)); + if(n < (int) sizeof(spaces)) + printf("%.*s", (int) sizeof(spaces) - n, spaces); + } else { + acutest_test_already_logged_ = 1; + } + } +} + +static void +acutest_finish_test_line_(int result) +{ + if(acutest_tap_) { + const char* str = (result == 0) ? "ok" : "not ok"; + + printf("%s %d - %s\n", str, acutest_current_index_ + 1, acutest_current_test_->name); + + if(result == 0 && acutest_timer_) { + printf("# Duration: "); + acutest_timer_print_diff_(); + printf("\n"); + } + } else { + int color = (result == 0) ? ACUTEST_COLOR_GREEN_INTENSIVE_ : ACUTEST_COLOR_RED_INTENSIVE_; + const char* str = (result == 0) ? "OK" : "FAILED"; + printf("[ "); + acutest_colored_printf_(color, "%s", str); + printf(" ]"); + + if(result == 0 && acutest_timer_) { + printf(" "); + acutest_timer_print_diff_(); + } + + printf("\n"); + } +} + +static void +acutest_line_indent_(int level) +{ + static const char spaces[] = " "; + int n = level * 2; + + if(acutest_tap_ && n > 0) { + n--; + printf("#"); + } + + while(n > 16) { + printf("%s", spaces); + n -= 16; + } + printf("%.*s", n, spaces); +} + +int ACUTEST_ATTRIBUTE_(format (printf, 4, 5)) +acutest_check_(int cond, const char* file, int line, const char* fmt, ...) +{ + const char *result_str; + int result_color; + int verbose_level; + + if(cond) { + result_str = "ok"; + result_color = ACUTEST_COLOR_GREEN_; + verbose_level = 3; + } else { + if(!acutest_test_already_logged_ && acutest_current_test_ != NULL) + acutest_finish_test_line_(-1); + + result_str = "failed"; + result_color = ACUTEST_COLOR_RED_; + verbose_level = 2; + acutest_test_failures_++; + acutest_test_already_logged_++; + } + + if(acutest_verbose_level_ >= verbose_level) { + va_list args; + + if(!acutest_case_already_logged_ && acutest_case_name_[0]) { + acutest_line_indent_(1); + acutest_colored_printf_(ACUTEST_COLOR_DEFAULT_INTENSIVE_, "Case %s:\n", acutest_case_name_); + acutest_test_already_logged_++; + acutest_case_already_logged_++; + } + + acutest_line_indent_(acutest_case_name_[0] ? 2 : 1); + if(file != NULL) { +#ifdef ACUTEST_WIN_ + const char* lastsep1 = strrchr(file, '\\'); + const char* lastsep2 = strrchr(file, '/'); + if(lastsep1 == NULL) + lastsep1 = file-1; + if(lastsep2 == NULL) + lastsep2 = file-1; + file = (lastsep1 > lastsep2 ? lastsep1 : lastsep2) + 1; +#else + const char* lastsep = strrchr(file, '/'); + if(lastsep != NULL) + file = lastsep+1; +#endif + printf("%s:%d: Check ", file, line); + } + + va_start(args, fmt); + vprintf(fmt, args); + va_end(args); + + printf("... "); + acutest_colored_printf_(result_color, "%s", result_str); + printf("\n"); + acutest_test_already_logged_++; + } + + acutest_cond_failed_ = (cond == 0); + return !acutest_cond_failed_; +} + +void ACUTEST_ATTRIBUTE_(format (printf, 1, 2)) +acutest_case_(const char* fmt, ...) +{ + va_list args; + + if(acutest_verbose_level_ < 2) + return; + + if(acutest_case_name_[0]) { + acutest_case_already_logged_ = 0; + acutest_case_name_[0] = '\0'; + } + + if(fmt == NULL) + return; + + va_start(args, fmt); + vsnprintf(acutest_case_name_, sizeof(acutest_case_name_) - 1, fmt, args); + va_end(args); + acutest_case_name_[sizeof(acutest_case_name_) - 1] = '\0'; + + if(acutest_verbose_level_ >= 3) { + acutest_line_indent_(1); + acutest_colored_printf_(ACUTEST_COLOR_DEFAULT_INTENSIVE_, "Case %s:\n", acutest_case_name_); + acutest_test_already_logged_++; + acutest_case_already_logged_++; + } +} + +void ACUTEST_ATTRIBUTE_(format (printf, 1, 2)) +acutest_message_(const char* fmt, ...) +{ + char buffer[TEST_MSG_MAXSIZE]; + char* line_beg; + char* line_end; + va_list args; + + if(acutest_verbose_level_ < 2) + return; + + /* We allow extra message only when something is already wrong in the + * current test. */ + if(acutest_current_test_ == NULL || !acutest_cond_failed_) + return; + + va_start(args, fmt); + vsnprintf(buffer, TEST_MSG_MAXSIZE, fmt, args); + va_end(args); + buffer[TEST_MSG_MAXSIZE-1] = '\0'; + + line_beg = buffer; + while(1) { + line_end = strchr(line_beg, '\n'); + if(line_end == NULL) + break; + acutest_line_indent_(acutest_case_name_[0] ? 3 : 2); + printf("%.*s\n", (int)(line_end - line_beg), line_beg); + line_beg = line_end + 1; + } + if(line_beg[0] != '\0') { + acutest_line_indent_(acutest_case_name_[0] ? 3 : 2); + printf("%s\n", line_beg); + } +} + +void +acutest_dump_(const char* title, const void* addr, size_t size) +{ + static const size_t BYTES_PER_LINE = 16; + size_t line_beg; + size_t truncate = 0; + + if(acutest_verbose_level_ < 2) + return; + + /* We allow extra message only when something is already wrong in the + * current test. */ + if(acutest_current_test_ == NULL || !acutest_cond_failed_) + return; + + if(size > TEST_DUMP_MAXSIZE) { + truncate = size - TEST_DUMP_MAXSIZE; + size = TEST_DUMP_MAXSIZE; + } + + acutest_line_indent_(acutest_case_name_[0] ? 3 : 2); + printf((title[strlen(title)-1] == ':') ? "%s\n" : "%s:\n", title); + + for(line_beg = 0; line_beg < size; line_beg += BYTES_PER_LINE) { + size_t line_end = line_beg + BYTES_PER_LINE; + size_t off; + + acutest_line_indent_(acutest_case_name_[0] ? 4 : 3); + printf("%08lx: ", (unsigned long)line_beg); + for(off = line_beg; off < line_end; off++) { + if(off < size) + printf(" %02x", ((const unsigned char*)addr)[off]); + else + printf(" "); + } + + printf(" "); + for(off = line_beg; off < line_end; off++) { + unsigned char byte = ((const unsigned char*)addr)[off]; + if(off < size) + printf("%c", (iscntrl(byte) ? '.' : byte)); + else + break; + } + + printf("\n"); + } + + if(truncate > 0) { + acutest_line_indent_(acutest_case_name_[0] ? 4 : 3); + printf(" ... (and more %u bytes)\n", (unsigned) truncate); + } +} + +/* This is called just before each test */ +static void +acutest_init_(const char *test_name) +{ +#ifdef TEST_INIT + TEST_INIT + ; /* Allow for a single unterminated function call */ +#endif + + /* Suppress any warnings about unused variable. */ + (void) test_name; +} + +/* This is called after each test */ +static void +acutest_fini_(const char *test_name) +{ +#ifdef TEST_FINI + TEST_FINI + ; /* Allow for a single unterminated function call */ +#endif + + /* Suppress any warnings about unused variable. */ + (void) test_name; +} + +void +acutest_abort_(void) +{ + if(acutest_abort_has_jmp_buf_) { + longjmp(acutest_abort_jmp_buf_, 1); + } else { + if(acutest_current_test_ != NULL) + acutest_fini_(acutest_current_test_->name); + abort(); + } +} + +static void +acutest_list_names_(void) +{ + const struct acutest_test_* test; + + printf("Unit tests:\n"); + for(test = ´st_list_[0]; test->func != NULL; test++) + printf(" %s\n", test->name); +} + +static void +acutest_remember_(int i) +{ + if(acutest_test_data_[i].flags & ACUTEST_FLAG_RUN_) + return; + + acutest_test_data_[i].flags |= ACUTEST_FLAG_RUN_; + acutest_count_++; +} + +static void +acutest_set_success_(int i, int success) +{ + acutest_test_data_[i].flags |= success ? ACUTEST_FLAG_SUCCESS_ : ACUTEST_FLAG_FAILURE_; +} + +static void +acutest_set_duration_(int i, double duration) +{ + acutest_test_data_[i].duration = duration; +} + +static int +acutest_name_contains_word_(const char* name, const char* pattern) +{ + static const char word_delim[] = " \t-_/.,:;"; + const char* substr; + size_t pattern_len; + + pattern_len = strlen(pattern); + + substr = strstr(name, pattern); + while(substr != NULL) { + int starts_on_word_boundary = (substr == name || strchr(word_delim, substr[-1]) != NULL); + int ends_on_word_boundary = (substr[pattern_len] == '\0' || strchr(word_delim, substr[pattern_len]) != NULL); + + if(starts_on_word_boundary && ends_on_word_boundary) + return 1; + + substr = strstr(substr+1, pattern); + } + + return 0; +} + +static int +acutest_lookup_(const char* pattern) +{ + int i; + int n = 0; + + /* Try exact match. */ + for(i = 0; i < (int) acutest_list_size_; i++) { + if(strcmp(acutest_list_[i].name, pattern) == 0) { + acutest_remember_(i); + n++; + break; + } + } + if(n > 0) + return n; + + /* Try word match. */ + for(i = 0; i < (int) acutest_list_size_; i++) { + if(acutest_name_contains_word_(acutest_list_[i].name, pattern)) { + acutest_remember_(i); + n++; + } + } + if(n > 0) + return n; + + /* Try relaxed match. */ + for(i = 0; i < (int) acutest_list_size_; i++) { + if(strstr(acutest_list_[i].name, pattern) != NULL) { + acutest_remember_(i); + n++; + } + } + + return n; +} + + +/* Called if anything goes bad in Acutest, or if the unit test ends in other + * way then by normal returning from its function (e.g. exception or some + * abnormal child process termination). */ +static void ACUTEST_ATTRIBUTE_(format (printf, 1, 2)) +acutest_error_(const char* fmt, ...) +{ + if(acutest_verbose_level_ == 0) + return; + + if(acutest_verbose_level_ >= 2) { + va_list args; + + acutest_line_indent_(1); + if(acutest_verbose_level_ >= 3) + acutest_colored_printf_(ACUTEST_COLOR_RED_INTENSIVE_, "ERROR: "); + va_start(args, fmt); + vprintf(fmt, args); + va_end(args); + printf("\n"); + } + + if(acutest_verbose_level_ >= 3) { + printf("\n"); + } +} + +/* Call directly the given test unit function. */ +static int +acutest_do_run_(const struct acutest_test_* test, int index) +{ + int status = -1; + + acutest_was_aborted_ = 0; + acutest_current_test_ = test; + acutest_current_index_ = index; + acutest_test_failures_ = 0; + acutest_test_already_logged_ = 0; + acutest_cond_failed_ = 0; + +#ifdef __cplusplus + try { +#endif + acutest_init_(test->name); + acutest_begin_test_line_(test); + + /* This is good to do in case the test unit crashes. */ + fflush(stdout); + fflush(stderr); + + if(!acutest_worker_) { + acutest_abort_has_jmp_buf_ = 1; + if(setjmp(acutest_abort_jmp_buf_) != 0) { + acutest_was_aborted_ = 1; + goto aborted; + } + } + + acutest_timer_get_time_(´st_timer_start_); + test->func(); + aborted: + acutest_abort_has_jmp_buf_ = 0; + acutest_timer_get_time_(´st_timer_end_); + + if(acutest_verbose_level_ >= 3) { + acutest_line_indent_(1); + if(acutest_test_failures_ == 0) { + acutest_colored_printf_(ACUTEST_COLOR_GREEN_INTENSIVE_, "SUCCESS: "); + printf("All conditions have passed.\n"); + + if(acutest_timer_) { + acutest_line_indent_(1); + printf("Duration: "); + acutest_timer_print_diff_(); + printf("\n"); + } + } else { + acutest_colored_printf_(ACUTEST_COLOR_RED_INTENSIVE_, "FAILED: "); + if(!acutest_was_aborted_) { + printf("%d condition%s %s failed.\n", + acutest_test_failures_, + (acutest_test_failures_ == 1) ? "" : "s", + (acutest_test_failures_ == 1) ? "has" : "have"); + } else { + printf("Aborted.\n"); + } + } + printf("\n"); + } else if(acutest_verbose_level_ >= 1 && acutest_test_failures_ == 0) { + acutest_finish_test_line_(0); + } + + status = (acutest_test_failures_ == 0) ? 0 : -1; + +#ifdef __cplusplus + } catch(std::exception& e) { + const char* what = e.what(); + acutest_check_(0, NULL, 0, "Threw std::exception"); + if(what != NULL) + acutest_message_("std::exception::what(): %s", what); + + if(acutest_verbose_level_ >= 3) { + acutest_line_indent_(1); + acutest_colored_printf_(ACUTEST_COLOR_RED_INTENSIVE_, "FAILED: "); + printf("C++ exception.\n\n"); + } + } catch(...) { + acutest_check_(0, NULL, 0, "Threw an exception"); + + if(acutest_verbose_level_ >= 3) { + acutest_line_indent_(1); + acutest_colored_printf_(ACUTEST_COLOR_RED_INTENSIVE_, "FAILED: "); + printf("C++ exception.\n\n"); + } + } +#endif + + acutest_fini_(test->name); + acutest_case_(NULL); + acutest_current_test_ = NULL; + + return status; +} + +/* Trigger the unit test. If possible (and not suppressed) it starts a child + * process who calls acutest_do_run_(), otherwise it calls acutest_do_run_() + * directly. */ +static void +acutest_run_(const struct acutest_test_* test, int index, int master_index) +{ + int failed = 1; + acutest_timer_type_ start, end; + + acutest_current_test_ = test; + acutest_test_already_logged_ = 0; + acutest_timer_get_time_(&start); + + if(!acutest_no_exec_) { + +#if defined(ACUTEST_UNIX_) + + pid_t pid; + int exit_code; + + /* Make sure the child starts with empty I/O buffers. */ + fflush(stdout); + fflush(stderr); + + pid = fork(); + if(pid == (pid_t)-1) { + acutest_error_("Cannot fork. %s [%d]", strerror(errno), errno); + failed = 1; + } else if(pid == 0) { + /* Child: Do the test. */ + acutest_worker_ = 1; + failed = (acutest_do_run_(test, index) != 0); + acutest_exit_(failed ? 1 : 0); + } else { + /* Parent: Wait until child terminates and analyze its exit code. */ + waitpid(pid, &exit_code, 0); + if(WIFEXITED(exit_code)) { + switch(WEXITSTATUS(exit_code)) { + case 0: failed = 0; break; /* test has passed. */ + case 1: /* noop */ break; /* "normal" failure. */ + default: acutest_error_("Unexpected exit code [%d]", WEXITSTATUS(exit_code)); + } + } else if(WIFSIGNALED(exit_code)) { + char tmp[32]; + const char* signame; + switch(WTERMSIG(exit_code)) { + case SIGINT: signame = "SIGINT"; break; + case SIGHUP: signame = "SIGHUP"; break; + case SIGQUIT: signame = "SIGQUIT"; break; + case SIGABRT: signame = "SIGABRT"; break; + case SIGKILL: signame = "SIGKILL"; break; + case SIGSEGV: signame = "SIGSEGV"; break; + case SIGILL: signame = "SIGILL"; break; + case SIGTERM: signame = "SIGTERM"; break; + default: sprintf(tmp, "signal %d", WTERMSIG(exit_code)); signame = tmp; break; + } + acutest_error_("Test interrupted by %s.", signame); + } else { + acutest_error_("Test ended in an unexpected way [%d].", exit_code); + } + } + +#elif defined(ACUTEST_WIN_) + + char buffer[512] = {0}; + STARTUPINFOA startupInfo; + PROCESS_INFORMATION processInfo; + DWORD exitCode; + + /* Windows has no fork(). So we propagate all info into the child + * through a command line arguments. */ + _snprintf(buffer, sizeof(buffer)-1, + "%s --worker=%d %s --no-exec --no-summary %s --verbose=%d --color=%s -- \"%s\"", + acutest_argv0_, index, acutest_timer_ ? "--time" : "", + acutest_tap_ ? "--tap" : "", acutest_verbose_level_, + acutest_colorize_ ? "always" : "never", + test->name); + memset(&startupInfo, 0, sizeof(startupInfo)); + startupInfo.cb = sizeof(STARTUPINFO); + if(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo)) { + WaitForSingleObject(processInfo.hProcess, INFINITE); + GetExitCodeProcess(processInfo.hProcess, &exitCode); + CloseHandle(processInfo.hThread); + CloseHandle(processInfo.hProcess); + failed = (exitCode != 0); + if(exitCode > 1) { + switch(exitCode) { + case 3: acutest_error_("Aborted."); break; + case 0xC0000005: acutest_error_("Access violation."); break; + default: acutest_error_("Test ended in an unexpected way [%lu].", exitCode); break; + } + } + } else { + acutest_error_("Cannot create unit test subprocess [%ld].", GetLastError()); + failed = 1; + } + +#else + + /* A platform where we don't know how to run child process. */ + failed = (acutest_do_run_(test, index) != 0); + +#endif + + } else { + /* Child processes suppressed through --no-exec. */ + failed = (acutest_do_run_(test, index) != 0); + } + acutest_timer_get_time_(&end); + + acutest_current_test_ = NULL; + + acutest_stat_run_units_++; + if(failed) + acutest_stat_failed_units_++; + + acutest_set_success_(master_index, !failed); + acutest_set_duration_(master_index, acutest_timer_diff_(start, end)); +} + +#if defined(ACUTEST_WIN_) +/* Callback for SEH events. */ +static LONG CALLBACK +acutest_seh_exception_filter_(EXCEPTION_POINTERS *ptrs) +{ + acutest_check_(0, NULL, 0, "Unhandled SEH exception"); + acutest_message_("Exception code: 0x%08lx", ptrs->ExceptionRecord->ExceptionCode); + acutest_message_("Exception address: 0x%p", ptrs->ExceptionRecord->ExceptionAddress); + + fflush(stdout); + fflush(stderr); + + return EXCEPTION_EXECUTE_HANDLER; +} +#endif + + +#define ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ 0x0001 +#define ACUTEST_CMDLINE_OPTFLAG_REQUIREDARG_ 0x0002 + +#define ACUTEST_CMDLINE_OPTID_NONE_ 0 +#define ACUTEST_CMDLINE_OPTID_UNKNOWN_ (-0x7fffffff + 0) +#define ACUTEST_CMDLINE_OPTID_MISSINGARG_ (-0x7fffffff + 1) +#define ACUTEST_CMDLINE_OPTID_BOGUSARG_ (-0x7fffffff + 2) + +typedef struct acutest_test_CMDLINE_OPTION_ { + char shortname; + const char* longname; + int id; + unsigned flags; +} ACUTEST_CMDLINE_OPTION_; + +static int +acutest_cmdline_handle_short_opt_group_(const ACUTEST_CMDLINE_OPTION_* options, + const char* arggroup, + int (*callback)(int /*optval*/, const char* /*arg*/)) +{ + const ACUTEST_CMDLINE_OPTION_* opt; + int i; + int ret = 0; + + for(i = 0; arggroup[i] != '\0'; i++) { + for(opt = options; opt->id != 0; opt++) { + if(arggroup[i] == opt->shortname) + break; + } + + if(opt->id != 0 && !(opt->flags & ACUTEST_CMDLINE_OPTFLAG_REQUIREDARG_)) { + ret = callback(opt->id, NULL); + } else { + /* Unknown option. */ + char badoptname[3]; + badoptname[0] = '-'; + badoptname[1] = arggroup[i]; + badoptname[2] = '\0'; + ret = callback((opt->id != 0 ? ACUTEST_CMDLINE_OPTID_MISSINGARG_ : ACUTEST_CMDLINE_OPTID_UNKNOWN_), + badoptname); + } + + if(ret != 0) + break; + } + + return ret; +} + +#define ACUTEST_CMDLINE_AUXBUF_SIZE_ 32 + +static int +acutest_cmdline_read_(const ACUTEST_CMDLINE_OPTION_* options, int argc, char** argv, + int (*callback)(int /*optval*/, const char* /*arg*/)) +{ + + const ACUTEST_CMDLINE_OPTION_* opt; + char auxbuf[ACUTEST_CMDLINE_AUXBUF_SIZE_+1]; + int after_doubledash = 0; + int i = 1; + int ret = 0; + + auxbuf[ACUTEST_CMDLINE_AUXBUF_SIZE_] = '\0'; + + while(i < argc) { + if(after_doubledash || strcmp(argv[i], "-") == 0) { + /* Non-option argument. */ + ret = callback(ACUTEST_CMDLINE_OPTID_NONE_, argv[i]); + } else if(strcmp(argv[i], "--") == 0) { + /* End of options. All the remaining members are non-option arguments. */ + after_doubledash = 1; + } else if(argv[i][0] != '-') { + /* Non-option argument. */ + ret = callback(ACUTEST_CMDLINE_OPTID_NONE_, argv[i]); + } else { + for(opt = options; opt->id != 0; opt++) { + if(opt->longname != NULL && strncmp(argv[i], "--", 2) == 0) { + size_t len = strlen(opt->longname); + if(strncmp(argv[i]+2, opt->longname, len) == 0) { + /* Regular long option. */ + if(argv[i][2+len] == '\0') { + /* with no argument provided. */ + if(!(opt->flags & ACUTEST_CMDLINE_OPTFLAG_REQUIREDARG_)) + ret = callback(opt->id, NULL); + else + ret = callback(ACUTEST_CMDLINE_OPTID_MISSINGARG_, argv[i]); + break; + } else if(argv[i][2+len] == '=') { + /* with an argument provided. */ + if(opt->flags & (ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ | ACUTEST_CMDLINE_OPTFLAG_REQUIREDARG_)) { + ret = callback(opt->id, argv[i]+2+len+1); + } else { + sprintf(auxbuf, "--%s", opt->longname); + ret = callback(ACUTEST_CMDLINE_OPTID_BOGUSARG_, auxbuf); + } + break; + } else { + continue; + } + } + } else if(opt->shortname != '\0' && argv[i][0] == '-') { + if(argv[i][1] == opt->shortname) { + /* Regular short option. */ + if(opt->flags & ACUTEST_CMDLINE_OPTFLAG_REQUIREDARG_) { + if(argv[i][2] != '\0') + ret = callback(opt->id, argv[i]+2); + else if(i+1 < argc) + ret = callback(opt->id, argv[++i]); + else + ret = callback(ACUTEST_CMDLINE_OPTID_MISSINGARG_, argv[i]); + break; + } else { + ret = callback(opt->id, NULL); + + /* There might be more (argument-less) short options + * grouped together. */ + if(ret == 0 && argv[i][2] != '\0') + ret = acutest_cmdline_handle_short_opt_group_(options, argv[i]+2, callback); + break; + } + } + } + } + + if(opt->id == 0) { /* still not handled? */ + if(argv[i][0] != '-') { + /* Non-option argument. */ + ret = callback(ACUTEST_CMDLINE_OPTID_NONE_, argv[i]); + } else { + /* Unknown option. */ + char* badoptname = argv[i]; + + if(strncmp(badoptname, "--", 2) == 0) { + /* Strip any argument from the long option. */ + char* assignment = strchr(badoptname, '='); + if(assignment != NULL) { + size_t len = assignment - badoptname; + if(len > ACUTEST_CMDLINE_AUXBUF_SIZE_) + len = ACUTEST_CMDLINE_AUXBUF_SIZE_; + strncpy(auxbuf, badoptname, len); + auxbuf[len] = '\0'; + badoptname = auxbuf; + } + } + + ret = callback(ACUTEST_CMDLINE_OPTID_UNKNOWN_, badoptname); + } + } + } + + if(ret != 0) + return ret; + i++; + } + + return ret; +} + +static void +acutest_help_(void) +{ + printf("Usage: %s [options] [test...]\n", acutest_argv0_); + printf("\n"); + printf("Run the specified unit tests; or if the option '--skip' is used, run all\n"); + printf("tests in the suite but those listed. By default, if no tests are specified\n"); + printf("on the command line, all unit tests in the suite are run.\n"); + printf("\n"); + printf("Options:\n"); + printf(" -s, --skip Execute all unit tests but the listed ones\n"); + printf(" --exec[=WHEN] If supported, execute unit tests as child processes\n"); + printf(" (WHEN is one of 'auto', 'always', 'never')\n"); + printf(" -E, --no-exec Same as --exec=never\n"); +#if defined ACUTEST_WIN_ + printf(" -t, --time Measure test duration\n"); +#elif defined ACUTEST_HAS_POSIX_TIMER_ + printf(" -t, --time Measure test duration (real time)\n"); + printf(" --time=TIMER Measure test duration, using given timer\n"); + printf(" (TIMER is one of 'real', 'cpu')\n"); +#endif + printf(" --no-summary Suppress printing of test results summary\n"); + printf(" --tap Produce TAP-compliant output\n"); + printf(" (See https://testanything.org/)\n"); + printf(" -x, --xml-output=FILE Enable XUnit output to the given file\n"); + printf(" -l, --list List unit tests in the suite and exit\n"); + printf(" -v, --verbose Make output more verbose\n"); + printf(" --verbose=LEVEL Set verbose level to LEVEL:\n"); + printf(" 0 ... Be silent\n"); + printf(" 1 ... Output one line per test (and summary)\n"); + printf(" 2 ... As 1 and failed conditions (this is default)\n"); + printf(" 3 ... As 1 and all conditions (and extended summary)\n"); + printf(" -q, --quiet Same as --verbose=0\n"); + printf(" --color[=WHEN] Enable colorized output\n"); + printf(" (WHEN is one of 'auto', 'always', 'never')\n"); + printf(" --no-color Same as --color=never\n"); + printf(" -h, --help Display this help and exit\n"); + + if(acutest_list_size_ < 16) { + printf("\n"); + acutest_list_names_(); + } +} + +static const ACUTEST_CMDLINE_OPTION_ acutest_cmdline_options_[] = { + { 's', "skip", 's', 0 }, + { 0, "exec", 'e', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, + { 'E', "no-exec", 'E', 0 }, +#if defined ACUTEST_WIN_ + { 't', "time", 't', 0 }, + { 0, "timer", 't', 0 }, /* kept for compatibility */ +#elif defined ACUTEST_HAS_POSIX_TIMER_ + { 't', "time", 't', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, + { 0, "timer", 't', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, /* kept for compatibility */ +#endif + { 0, "no-summary", 'S', 0 }, + { 0, "tap", 'T', 0 }, + { 'l', "list", 'l', 0 }, + { 'v', "verbose", 'v', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, + { 'q', "quiet", 'q', 0 }, + { 0, "color", 'c', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, + { 0, "no-color", 'C', 0 }, + { 'h', "help", 'h', 0 }, + { 0, "worker", 'w', ACUTEST_CMDLINE_OPTFLAG_REQUIREDARG_ }, /* internal */ + { 'x', "xml-output", 'x', ACUTEST_CMDLINE_OPTFLAG_REQUIREDARG_ }, + { 0, NULL, 0, 0 } +}; + +static int +acutest_cmdline_callback_(int id, const char* arg) +{ + switch(id) { + case 's': + acutest_skip_mode_ = 1; + break; + + case 'e': + if(arg == NULL || strcmp(arg, "always") == 0) { + acutest_no_exec_ = 0; + } else if(strcmp(arg, "never") == 0) { + acutest_no_exec_ = 1; + } else if(strcmp(arg, "auto") == 0) { + /*noop*/ + } else { + fprintf(stderr, "%s: Unrecognized argument '%s' for option --exec.\n", acutest_argv0_, arg); + fprintf(stderr, "Try '%s --help' for more information.\n", acutest_argv0_); + acutest_exit_(2); + } + break; + + case 'E': + acutest_no_exec_ = 1; + break; + + case 't': +#if defined ACUTEST_WIN_ || defined ACUTEST_HAS_POSIX_TIMER_ + if(arg == NULL || strcmp(arg, "real") == 0) { + acutest_timer_ = 1; +#ifndef ACUTEST_WIN_ + } else if(strcmp(arg, "cpu") == 0) { + acutest_timer_ = 2; +#endif + } else { + fprintf(stderr, "%s: Unrecognized argument '%s' for option --time.\n", acutest_argv0_, arg); + fprintf(stderr, "Try '%s --help' for more information.\n", acutest_argv0_); + acutest_exit_(2); + } +#endif + break; + + case 'S': + acutest_no_summary_ = 1; + break; + + case 'T': + acutest_tap_ = 1; + break; + + case 'l': + acutest_list_names_(); + acutest_exit_(0); + break; + + case 'v': + acutest_verbose_level_ = (arg != NULL ? atoi(arg) : acutest_verbose_level_+1); + break; + + case 'q': + acutest_verbose_level_ = 0; + break; + + case 'c': + if(arg == NULL || strcmp(arg, "always") == 0) { + acutest_colorize_ = 1; + } else if(strcmp(arg, "never") == 0) { + acutest_colorize_ = 0; + } else if(strcmp(arg, "auto") == 0) { + /*noop*/ + } else { + fprintf(stderr, "%s: Unrecognized argument '%s' for option --color.\n", acutest_argv0_, arg); + fprintf(stderr, "Try '%s --help' for more information.\n", acutest_argv0_); + acutest_exit_(2); + } + break; + + case 'C': + acutest_colorize_ = 0; + break; + + case 'h': + acutest_help_(); + acutest_exit_(0); + break; + + case 'w': + acutest_worker_ = 1; + acutest_worker_index_ = atoi(arg); + break; + case 'x': + acutest_xml_output_ = fopen(arg, "w"); + if (!acutest_xml_output_) { + fprintf(stderr, "Unable to open '%s': %s\n", arg, strerror(errno)); + acutest_exit_(2); + } + break; + + case 0: + if(acutest_lookup_(arg) == 0) { + fprintf(stderr, "%s: Unrecognized unit test '%s'\n", acutest_argv0_, arg); + fprintf(stderr, "Try '%s --list' for list of unit tests.\n", acutest_argv0_); + acutest_exit_(2); + } + break; + + case ACUTEST_CMDLINE_OPTID_UNKNOWN_: + fprintf(stderr, "Unrecognized command line option '%s'.\n", arg); + fprintf(stderr, "Try '%s --help' for more information.\n", acutest_argv0_); + acutest_exit_(2); + break; + + case ACUTEST_CMDLINE_OPTID_MISSINGARG_: + fprintf(stderr, "The command line option '%s' requires an argument.\n", arg); + fprintf(stderr, "Try '%s --help' for more information.\n", acutest_argv0_); + acutest_exit_(2); + break; + + case ACUTEST_CMDLINE_OPTID_BOGUSARG_: + fprintf(stderr, "The command line option '%s' does not expect an argument.\n", arg); + fprintf(stderr, "Try '%s --help' for more information.\n", acutest_argv0_); + acutest_exit_(2); + break; + } + + return 0; +} + + +#ifdef ACUTEST_LINUX_ +static int +acutest_is_tracer_present_(void) +{ + /* Must be large enough so the line 'TracerPid: ${PID}' can fit in. */ + static const int OVERLAP = 32; + + char buf[512]; + int tracer_present = 0; + int fd; + size_t n_read = 0; + + fd = open("/proc/self/status", O_RDONLY); + if(fd == -1) + return 0; + + while(1) { + static const char pattern[] = "TracerPid:"; + const char* field; + + while(n_read < sizeof(buf) - 1) { + ssize_t n; + + n = read(fd, buf + n_read, sizeof(buf) - 1 - n_read); + if(n <= 0) + break; + n_read += n; + } + buf[n_read] = '\0'; + + field = strstr(buf, pattern); + if(field != NULL && field < buf + sizeof(buf) - OVERLAP) { + pid_t tracer_pid = (pid_t) atoi(field + sizeof(pattern) - 1); + tracer_present = (tracer_pid != 0); + break; + } + + if(n_read == sizeof(buf) - 1) { + /* Move the tail with the potentially incomplete line we're looking + * for to the beginning of the buffer. */ + memmove(buf, buf + sizeof(buf) - 1 - OVERLAP, OVERLAP); + n_read = OVERLAP; + } else { + break; + } + } + + close(fd); + return tracer_present; +} +#endif + +#ifdef ACUTEST_MACOS_ +static bool +acutest_AmIBeingDebugged(void) +{ + int junk; + int mib[4]; + struct kinfo_proc info; + size_t size; + + // Initialize the flags so that, if sysctl fails for some bizarre + // reason, we get a predictable result. + info.kp_proc.p_flag = 0; + + // Initialize mib, which tells sysctl the info we want, in this case + // we're looking for information about a specific process ID. + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PID; + mib[3] = getpid(); + + // Call sysctl. + size = sizeof(info); + junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0); + assert(junk == 0); + + // We're being debugged if the P_TRACED flag is set. + return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); +} +#endif + +int +main(int argc, char** argv) +{ + int i; + + acutest_argv0_ = argv[0]; + +#if defined ACUTEST_UNIX_ + acutest_colorize_ = isatty(STDOUT_FILENO); +#elif defined ACUTEST_WIN_ + #if defined _BORLANDC_ + acutest_colorize_ = isatty(_fileno(stdout)); + #else + acutest_colorize_ = _isatty(_fileno(stdout)); + #endif +#else + acutest_colorize_ = 0; +#endif + + /* Count all test units */ + acutest_list_size_ = 0; + for(i = 0; acutest_list_[i].func != NULL; i++) + acutest_list_size_++; + + acutest_test_data_ = (struct acutest_test_data_*)calloc(acutest_list_size_, sizeof(struct acutest_test_data_)); + if(acutest_test_data_ == NULL) { + fprintf(stderr, "Out of memory.\n"); + acutest_exit_(2); + } + + /* Parse options */ + acutest_cmdline_read_(acutest_cmdline_options_, argc, argv, acutest_cmdline_callback_); + + /* Initialize the proper timer. */ + acutest_timer_init_(); + +#if defined(ACUTEST_WIN_) + SetUnhandledExceptionFilter(acutest_seh_exception_filter_); +#ifdef _MSC_VER + _set_abort_behavior(0, _WRITE_ABORT_MSG); +#endif +#endif + + /* By default, we want to run all tests. */ + if(acutest_count_ == 0) { + for(i = 0; acutest_list_[i].func != NULL; i++) + acutest_remember_(i); + } + + /* Guess whether we want to run unit tests as child processes. */ + if(acutest_no_exec_ < 0) { + acutest_no_exec_ = 0; + + if(acutest_count_ <= 1) { + acutest_no_exec_ = 1; + } else { +#ifdef ACUTEST_WIN_ + if(IsDebuggerPresent()) + acutest_no_exec_ = 1; +#endif +#ifdef ACUTEST_LINUX_ + if(acutest_is_tracer_present_()) + acutest_no_exec_ = 1; +#endif +#ifdef ACUTEST_MACOS_ + if(acutest_AmIBeingDebugged()) + acutest_no_exec_ = 1; +#endif +#ifdef RUNNING_ON_VALGRIND + /* RUNNING_ON_VALGRIND is provided by optionally included */ + if(RUNNING_ON_VALGRIND) + acutest_no_exec_ = 1; +#endif + } + } + + if(acutest_tap_) { + /* TAP requires we know test result ("ok", "not ok") before we output + * anything about the test, and this gets problematic for larger verbose + * levels. */ + if(acutest_verbose_level_ > 2) + acutest_verbose_level_ = 2; + + /* TAP harness should provide some summary. */ + acutest_no_summary_ = 1; + + if(!acutest_worker_) + printf("1..%d\n", (int) acutest_count_); + } + + int index = acutest_worker_index_; + for(i = 0; acutest_list_[i].func != NULL; i++) { + int run = (acutest_test_data_[i].flags & ACUTEST_FLAG_RUN_); + if (acutest_skip_mode_) /* Run all tests except those listed. */ + run = !run; + if(run) + acutest_run_(´st_list_[i], index++, i); + } + + /* Write a summary */ + if(!acutest_no_summary_ && acutest_verbose_level_ >= 1) { + if(acutest_verbose_level_ >= 3) { + acutest_colored_printf_(ACUTEST_COLOR_DEFAULT_INTENSIVE_, "Summary:\n"); + + printf(" Count of all unit tests: %4d\n", (int) acutest_list_size_); + printf(" Count of run unit tests: %4d\n", acutest_stat_run_units_); + printf(" Count of failed unit tests: %4d\n", acutest_stat_failed_units_); + printf(" Count of skipped unit tests: %4d\n", (int) acutest_list_size_ - acutest_stat_run_units_); + } + + if(acutest_stat_failed_units_ == 0) { + acutest_colored_printf_(ACUTEST_COLOR_GREEN_INTENSIVE_, "SUCCESS:"); + printf(" All unit tests have passed.\n"); + } else { + acutest_colored_printf_(ACUTEST_COLOR_RED_INTENSIVE_, "FAILED:"); + printf(" %d of %d unit tests %s failed.\n", + acutest_stat_failed_units_, acutest_stat_run_units_, + (acutest_stat_failed_units_ == 1) ? "has" : "have"); + } + + if(acutest_verbose_level_ >= 3) + printf("\n"); + } + + if (acutest_xml_output_) { +#if defined ACUTEST_UNIX_ + char *suite_name = basename(argv[0]); +#elif defined ACUTEST_WIN_ + char suite_name[_MAX_FNAME]; + _splitpath(argv[0], NULL, NULL, suite_name, NULL); +#else + const char *suite_name = argv[0]; +#endif + fprintf(acutest_xml_output_, "\n"); + fprintf(acutest_xml_output_, "\n", + suite_name, (int)acutest_list_size_, acutest_stat_failed_units_, acutest_stat_failed_units_, + (int)acutest_list_size_ - acutest_stat_run_units_); + for(i = 0; acutest_list_[i].func != NULL; i++) { + struct acutest_test_data_ *details = ´st_test_data_[i]; + fprintf(acutest_xml_output_, " \n", acutest_list_[i].name, details->duration); + if (details->flags & ACUTEST_FLAG_FAILURE_) + fprintf(acutest_xml_output_, " \n"); + if (!(details->flags & ACUTEST_FLAG_FAILURE_) && !(details->flags & ACUTEST_FLAG_SUCCESS_)) + fprintf(acutest_xml_output_, " \n"); + fprintf(acutest_xml_output_, " \n"); + } + fprintf(acutest_xml_output_, "\n"); + fclose(acutest_xml_output_); + } + + acutest_cleanup_(); + + return (acutest_stat_failed_units_ == 0) ? 0 : 1; +} + + +#endif /* #ifndef TEST_NO_MAIN */ + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* #ifndef ACUTEST_H */ From 386d83ec9304919cc5b6df78a5784c19124da924 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Thu, 22 Feb 2024 17:57:58 +0100 Subject: [PATCH 03/21] feat: add initial routing function --- include/lnm/http/consts.h | 1 + include/lnm/http/router.h | 39 ++++++++++++++++ src/_include/lnm/http/router_internal.h | 28 +++--------- src/http/lnm_http_router.c | 59 ++++++++++++++++++++++++- 4 files changed, 103 insertions(+), 24 deletions(-) create mode 100644 include/lnm/http/router.h diff --git a/include/lnm/http/consts.h b/include/lnm/http/consts.h index f543bbb..d3c9b97 100644 --- a/include/lnm/http/consts.h +++ b/include/lnm/http/consts.h @@ -13,6 +13,7 @@ typedef enum lnm_http_method { lnm_http_method_patch, lnm_http_method_delete, lnm_http_method_head, + lnm_http_method_total, } lnm_http_method; extern const char *lnm_http_status_names[][32]; diff --git a/include/lnm/http/router.h b/include/lnm/http/router.h new file mode 100644 index 0000000..7b7d56b --- /dev/null +++ b/include/lnm/http/router.h @@ -0,0 +1,39 @@ +#ifndef LNM_HTTP_ROUTER +#define LNM_HTTP_ROUTER + +#include "lnm/common.h" +#include "lnm/http/consts.h" + +typedef struct lnm_http_route lnm_http_route; + +typedef struct lnm_http_router lnm_http_router; + +typedef enum lnm_http_route_err { + lnm_http_route_err_match = 0, + lnm_http_route_err_unknown_route = 1, + lnm_http_route_err_unknown_method = 2, +} lnm_http_route_err; + +/** + * Allocate and initialize a new http_router. + */ +lnm_err lnm_http_router_init(lnm_http_router **out); + +void lnm_http_router_free(lnm_http_router *router); + +lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, + lnm_http_method method, const char *path); + +/** + * Add all of the child router's routes to the parent router, under the given + * route prefix. + */ +lnm_err lnm_http_router_nest(lnm_http_router *parent, + const lnm_http_router *child, const char *prefix); + +lnm_http_route_err lnm_http_router_route(const lnm_http_route **out, + const lnm_http_router *router, + lnm_http_method method, + const char *path); + +#endif diff --git a/src/_include/lnm/http/router_internal.h b/src/_include/lnm/http/router_internal.h index e4f6bda..a2504fa 100644 --- a/src/_include/lnm/http/router_internal.h +++ b/src/_include/lnm/http/router_internal.h @@ -2,35 +2,19 @@ #define LNM_HTTP_ROUTER_INTERNAL #include "lnm/common.h" +#include "lnm/http/consts.h" +#include "lnm/http/router.h" -typedef struct lnm_http_route { -} lnm_http_route; +struct lnm_http_route {}; -typedef struct lnm_http_router { +struct lnm_http_router { struct lnm_http_router *exact_children[128]; struct lnm_http_router *single_segment_child; - lnm_http_route *route; -} lnm_http_router; - -/** - * Allocate and initialize a new http_router. - */ -lnm_err lnm_http_router_init(lnm_http_router **out); - -void lnm_http_router_free(lnm_http_router *router); + lnm_http_route *routes[lnm_http_method_total]; +}; lnm_err lnm_http_route_init(lnm_http_route **out); void lnm_http_route_free(lnm_http_route *route); -lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, - const char *path); - -/** - * Add all of the child router's routes to the parent router, under the given - * route prefix. - */ -lnm_err lnm_http_router_nest(lnm_http_router *parent, - const lnm_http_router *child, const char *prefix); - #endif diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index f5001f8..6dee3c8 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -1,6 +1,7 @@ #include #include "lnm/common.h" +#include "lnm/http/router.h" #include "lnm/http/router_internal.h" lnm_err lnm_http_router_init(lnm_http_router **out) { @@ -40,7 +41,7 @@ static bool is_ascii(const char *s) { } lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, - const char *path) { + lnm_http_method method, const char *path) { if (path[0] != '/' || !is_ascii(path)) { return lnm_err_invalid_route; } @@ -51,6 +52,7 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, switch (c) { case ':': LNM_RES(lnm_http_router_init(&http_router->single_segment_child)); + http_router = http_router->single_segment_child; // All other characters in the segment are ignored const char *next_slash_ptr = strchr(path, '/'); @@ -67,7 +69,60 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, } } - LNM_RES(lnm_http_route_init(out)); + if (http_router->routes[method] != NULL) { + return lnm_err_overlapping_route; + } + + LNM_RES(lnm_http_route_init(&http_router->routes[method])); + *out = http_router->routes[method]; return lnm_err_ok; } + +lnm_http_route_err lnm_http_router_route(const lnm_http_route **out, + const lnm_http_router *router, + lnm_http_method method, + const char *path) { + if (!is_ascii(path)) { + return lnm_http_route_err_unknown_route; + } + + if (*path == '\0') { + *out = router->routes[method]; + + return *out == NULL ? lnm_http_route_err_unknown_method + : lnm_http_route_err_match; + } + + lnm_http_route_err res = lnm_http_route_err_unknown_route; + lnm_http_router *exact_router = router->exact_children[(unsigned char)*path]; + + if (exact_router != NULL) { + lnm_http_route_err sub_res = + lnm_http_router_route(out, exact_router, method, path + 1); + + if (sub_res == lnm_http_route_err_match) { + return lnm_http_route_err_match; + } + + res = LNM_MAX(res, sub_res); + } + + lnm_http_router *single_segment_router = router->single_segment_child; + + if (single_segment_router != NULL) { + const char *next_slash_ptr = strchr(path, '/'); + path = next_slash_ptr == NULL ? strchr(path, '\0') : next_slash_ptr; + + lnm_http_route_err sub_res = + lnm_http_router_route(out, exact_router, method, path); + + if (sub_res == lnm_http_route_err_match) { + return lnm_http_route_err_match; + } + + res = LNM_MAX(res, sub_res); + } + + return res; +} From de4e509c9ce82d2d1376f7b15fe0a08dfb736703 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Thu, 22 Feb 2024 18:17:26 +0100 Subject: [PATCH 04/21] chore: started routing tests --- src/_include/lnm/http/router_internal.h | 1 + src/http/lnm_http_router.c | 29 ++++++++++++++++++++----- test/routing.c | 16 ++++++++++++++ 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/_include/lnm/http/router_internal.h b/src/_include/lnm/http/router_internal.h index a2504fa..b98b80f 100644 --- a/src/_include/lnm/http/router_internal.h +++ b/src/_include/lnm/http/router_internal.h @@ -11,6 +11,7 @@ struct lnm_http_router { struct lnm_http_router *exact_children[128]; struct lnm_http_router *single_segment_child; lnm_http_route *routes[lnm_http_method_total]; + bool represents_route; }; lnm_err lnm_http_route_init(lnm_http_route **out); diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index 6dee3c8..0fb127f 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -1,3 +1,4 @@ +#include #include #include "lnm/common.h" @@ -51,7 +52,10 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, switch (c) { case ':': - LNM_RES(lnm_http_router_init(&http_router->single_segment_child)); + if (http_router->single_segment_child == NULL) { + LNM_RES(lnm_http_router_init(&http_router->single_segment_child)); + } + http_router = http_router->single_segment_child; // All other characters in the segment are ignored @@ -62,7 +66,10 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, // TODO multi-segment wildcard break; default: - LNM_RES(lnm_http_router_init(&http_router->exact_children[c])); + if (http_router->exact_children[c] == NULL) { + LNM_RES(lnm_http_router_init(&http_router->exact_children[c])); + } + http_router = http_router->exact_children[c]; path++; break; @@ -74,7 +81,11 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, } LNM_RES(lnm_http_route_init(&http_router->routes[method])); - *out = http_router->routes[method]; + http_router->represents_route = true; + + if (out != NULL) { + *out = http_router->routes[method]; + } return lnm_err_ok; } @@ -88,10 +99,16 @@ lnm_http_route_err lnm_http_router_route(const lnm_http_route **out, } if (*path == '\0') { - *out = router->routes[method]; + if (!router->represents_route) { + return lnm_http_route_err_unknown_route; + } - return *out == NULL ? lnm_http_route_err_unknown_method - : lnm_http_route_err_match; + if (out != NULL) { + *out = router->routes[method]; + } + + return router->routes[method] == NULL ? lnm_http_route_err_unknown_method + : lnm_http_route_err_match; } lnm_http_route_err res = lnm_http_route_err_unknown_route; diff --git a/test/routing.c b/test/routing.c index acab1cc..a42923e 100644 --- a/test/routing.c +++ b/test/routing.c @@ -1,5 +1,21 @@ #include "test.h" +#include "lnm/http/router.h" + +void test_routing_simple() { + lnm_http_router *router; + lnm_http_router_init(&router); + + lnm_http_router_add(NULL, router, lnm_http_method_get, "/test"); + lnm_http_router_add(NULL, router, lnm_http_method_get, "/test/test2"); + + TEST_CHECK(lnm_http_router_route(NULL, router, lnm_http_method_get, "/test") == lnm_http_route_err_match); + TEST_CHECK(lnm_http_router_route(NULL, router, lnm_http_method_get, "/test/te") == lnm_http_route_err_unknown_route); + TEST_CHECK(lnm_http_router_route(NULL, router, lnm_http_method_head, "/test/test2") == lnm_http_route_err_unknown_method); + TEST_CHECK(lnm_http_router_route(NULL, router, lnm_http_method_get, "/test/test2") == lnm_http_route_err_match); +} + TEST_LIST = { + { "routing simple", test_routing_simple }, { NULL, NULL } }; From f652fa08c1c45d4393c0cae3a0f638da8e85004e Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Thu, 22 Feb 2024 22:15:19 +0100 Subject: [PATCH 05/21] feat(routing): support matching key segments in routes --- include/lnm/common.h | 1 + include/lnm/http/router.h | 13 +- src/_include/lnm/http/router_internal.h | 18 ++- src/http/lnm_http_router.c | 193 +++++++++++++++++++----- test/routing.c | 21 ++- 5 files changed, 207 insertions(+), 39 deletions(-) diff --git a/include/lnm/common.h b/include/lnm/common.h index 3ada2a4..eba90a8 100644 --- a/include/lnm/common.h +++ b/include/lnm/common.h @@ -32,6 +32,7 @@ typedef enum lnm_err { lnm_err_not_setup, lnm_err_bad_regex, lnm_err_not_found, + lnm_err_already_present, lnm_err_invalid_route, lnm_err_overlapping_route, } lnm_err; diff --git a/include/lnm/http/router.h b/include/lnm/http/router.h index 7b7d56b..9fbc05b 100644 --- a/include/lnm/http/router.h +++ b/include/lnm/http/router.h @@ -1,11 +1,22 @@ #ifndef LNM_HTTP_ROUTER #define LNM_HTTP_ROUTER +#define LNM_HTTP_MAX_KEY_SEGMENTS 4 + #include "lnm/common.h" #include "lnm/http/consts.h" typedef struct lnm_http_route lnm_http_route; +typedef struct lnm_http_route_match { + const lnm_http_route *route; + lnm_http_method method; + struct { + size_t start; + size_t len; + } key_segments[LNM_HTTP_MAX_KEY_SEGMENTS]; +} lnm_http_route_match; + typedef struct lnm_http_router lnm_http_router; typedef enum lnm_http_route_err { @@ -31,7 +42,7 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, lnm_err lnm_http_router_nest(lnm_http_router *parent, const lnm_http_router *child, const char *prefix); -lnm_http_route_err lnm_http_router_route(const lnm_http_route **out, +lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, const lnm_http_router *router, lnm_http_method method, const char *path); diff --git a/src/_include/lnm/http/router_internal.h b/src/_include/lnm/http/router_internal.h index b98b80f..6c402d3 100644 --- a/src/_include/lnm/http/router_internal.h +++ b/src/_include/lnm/http/router_internal.h @@ -5,7 +5,23 @@ #include "lnm/http/consts.h" #include "lnm/http/router.h" -struct lnm_http_route {}; +typedef struct lnm_http_route_segment_trie { + struct lnm_http_route_segment_trie *children[128]; + size_t index; + bool represents_segment; +} lnm_http_route_segment_trie; + +lnm_err lnm_http_route_segment_trie_init(lnm_http_route_segment_trie **out); + +void lnm_http_route_segment_trie_free(lnm_http_route_segment_trie *trie); + +lnm_err lnm_http_route_key_segment_insert(lnm_http_route *route, + const char *key, size_t key_len, + size_t index); + +struct lnm_http_route { + lnm_http_route_segment_trie *key_segments; +}; struct lnm_http_router { struct lnm_http_router *exact_children[128]; diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index 0fb127f..6325deb 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -1,4 +1,3 @@ -#include #include #include "lnm/common.h" @@ -29,6 +28,71 @@ lnm_err lnm_http_route_init(lnm_http_route **out) { return lnm_err_ok; } +void lnm_http_route_free(lnm_http_route *route) { + if (route == NULL) { + return; + } + + lnm_http_route_segment_trie_free(route->key_segments); + free(route); +} + +lnm_err lnm_http_route_segment_trie_init(lnm_http_route_segment_trie **out) { + lnm_http_route_segment_trie *trie = + calloc(1, sizeof(lnm_http_route_segment_trie)); + + if (trie == NULL) { + return lnm_err_failed_alloc; + } + + *out = trie; + + return lnm_err_ok; +} + +void lnm_http_route_segment_trie_free(lnm_http_route_segment_trie *trie) { + if (trie == NULL) { + return; + } + + for (size_t i = 0; i < 128; i++) { + if (trie->children[i] != NULL) { + lnm_http_route_segment_trie_free(trie->children[i]); + } + } + + free(trie); +} + +lnm_err lnm_http_route_key_segment_insert(lnm_http_route *route, + const char *key, size_t key_len, + size_t index) { + if (route->key_segments == NULL) { + LNM_RES(lnm_http_route_segment_trie_init(&route->key_segments)); + } + + lnm_http_route_segment_trie *trie = route->key_segments; + + for (size_t key_index = 0; key_index < key_len; key_index++) { + unsigned char c = key[key_index]; + + if (trie->children[c] == NULL) { + LNM_RES(lnm_http_route_segment_trie_init(&trie->children[c])); + } + + trie = trie->children[c]; + } + + if (trie->represents_segment) { + return lnm_err_already_present; + } + + trie->represents_segment = true; + trie->index = index; + + return lnm_err_ok; +} + static bool is_ascii(const char *s) { while (*s != '0') { if (*s > 127) { @@ -47,27 +111,58 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, return lnm_err_invalid_route; } + lnm_http_route *route; + LNM_RES(lnm_http_route_init(&route)); + + size_t key_segments_count = 0; + lnm_err res = lnm_err_ok; + while (*path != '\0') { unsigned char c = *path; switch (c) { - case ':': + case ':': { + const char *next_slash_ptr = strchr(path, '/'); + const char *new_path = + next_slash_ptr == NULL ? strchr(path, '\0') : next_slash_ptr; + size_t key_len = new_path - path - 1; + + if (key_len == 0) { + res = lnm_err_invalid_route; + + goto end; + } + + res = lnm_http_route_key_segment_insert(route, path + 1, key_len, + key_segments_count); + + if (res != lnm_err_ok) { + goto end; + } + + key_segments_count++; + if (http_router->single_segment_child == NULL) { - LNM_RES(lnm_http_router_init(&http_router->single_segment_child)); + res = lnm_http_router_init(&http_router->single_segment_child); + + if (res != lnm_err_ok) { + goto end; + } } http_router = http_router->single_segment_child; - - // All other characters in the segment are ignored - const char *next_slash_ptr = strchr(path, '/'); - path = next_slash_ptr == NULL ? strchr(path, '\0') : next_slash_ptr; - break; + path = new_path; + } break; case '*': // TODO multi-segment wildcard break; default: if (http_router->exact_children[c] == NULL) { - LNM_RES(lnm_http_router_init(&http_router->exact_children[c])); + res = lnm_http_router_init(&http_router->exact_children[c]); + + if (res != lnm_err_ok) { + goto end; + } } http_router = http_router->exact_children[c]; @@ -77,34 +172,41 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, } if (http_router->routes[method] != NULL) { - return lnm_err_overlapping_route; + res = lnm_err_overlapping_route; + + goto end; } - LNM_RES(lnm_http_route_init(&http_router->routes[method])); + http_router->routes[method] = route; http_router->represents_route = true; +end: + if (res != lnm_err_ok) { + lnm_http_route_free(route); + + return res; + } + if (out != NULL) { - *out = http_router->routes[method]; + *out = route; } return lnm_err_ok; } -lnm_http_route_err lnm_http_router_route(const lnm_http_route **out, - const lnm_http_router *router, - lnm_http_method method, - const char *path) { - if (!is_ascii(path)) { - return lnm_http_route_err_unknown_route; - } - - if (*path == '\0') { +static lnm_http_route_err __lnm_http_router_route(lnm_http_route_match *out, + const lnm_http_router *router, + lnm_http_method method, + const char *path, + size_t path_index, + size_t matched_key_segments) { + if (path[path_index] == '\0') { if (!router->represents_route) { return lnm_http_route_err_unknown_route; } if (out != NULL) { - *out = router->routes[method]; + out->route = router->routes[method]; } return router->routes[method] == NULL ? lnm_http_route_err_unknown_method @@ -112,11 +214,12 @@ lnm_http_route_err lnm_http_router_route(const lnm_http_route **out, } lnm_http_route_err res = lnm_http_route_err_unknown_route; - lnm_http_router *exact_router = router->exact_children[(unsigned char)*path]; + const lnm_http_router *exact_router = + router->exact_children[(unsigned char)path[path_index]]; if (exact_router != NULL) { - lnm_http_route_err sub_res = - lnm_http_router_route(out, exact_router, method, path + 1); + lnm_http_route_err sub_res = __lnm_http_router_route( + out, exact_router, method, path, path_index + 1, matched_key_segments); if (sub_res == lnm_http_route_err_match) { return lnm_http_route_err_match; @@ -125,21 +228,43 @@ lnm_http_route_err lnm_http_router_route(const lnm_http_route **out, res = LNM_MAX(res, sub_res); } - lnm_http_router *single_segment_router = router->single_segment_child; + const lnm_http_router *single_segment_router = router->single_segment_child; if (single_segment_router != NULL) { - const char *next_slash_ptr = strchr(path, '/'); - path = next_slash_ptr == NULL ? strchr(path, '\0') : next_slash_ptr; + const char *next_slash_ptr = strchr(path + path_index, '/'); + const char *new_path = next_slash_ptr == NULL + ? strchr(path + path_index, '\0') + : next_slash_ptr; + size_t segment_len = new_path - (path + path_index); - lnm_http_route_err sub_res = - lnm_http_router_route(out, exact_router, method, path); + if (segment_len > 0) { + lnm_http_route_err sub_res = __lnm_http_router_route( + out, single_segment_router, method, path, path_index + segment_len, + matched_key_segments + 1); - if (sub_res == lnm_http_route_err_match) { - return lnm_http_route_err_match; + if (sub_res == lnm_http_route_err_match) { + if (out != NULL) { + out->key_segments[matched_key_segments].start = path_index; + out->key_segments[matched_key_segments].len = segment_len; + } + + return lnm_http_route_err_match; + } + + res = LNM_MAX(res, sub_res); } - - res = LNM_MAX(res, sub_res); } return res; } + +lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, + const lnm_http_router *router, + lnm_http_method method, + const char *path) { + if (!is_ascii(path)) { + return lnm_http_route_err_unknown_route; + } + + return __lnm_http_router_route(out, router, method, path, 0, 0); +} diff --git a/test/routing.c b/test/routing.c index a42923e..a1d6a05 100644 --- a/test/routing.c +++ b/test/routing.c @@ -6,13 +6,28 @@ void test_routing_simple() { lnm_http_router *router; lnm_http_router_init(&router); - lnm_http_router_add(NULL, router, lnm_http_method_get, "/test"); - lnm_http_router_add(NULL, router, lnm_http_method_get, "/test/test2"); + TEST_CHECK(lnm_http_router_add(NULL, router, lnm_http_method_get, "/test") == lnm_err_ok); + TEST_CHECK(lnm_http_router_add(NULL, router, lnm_http_method_get, "/test/test2") == lnm_err_ok); + TEST_CHECK(lnm_http_router_add(NULL, router, lnm_http_method_get, "/test/:hello") == lnm_err_ok); + TEST_CHECK(lnm_http_router_add(NULL, router, lnm_http_method_get, "/test/:hello/:second") == lnm_err_ok); TEST_CHECK(lnm_http_router_route(NULL, router, lnm_http_method_get, "/test") == lnm_http_route_err_match); - TEST_CHECK(lnm_http_router_route(NULL, router, lnm_http_method_get, "/test/te") == lnm_http_route_err_unknown_route); + TEST_CHECK(lnm_http_router_route(NULL, router, lnm_http_method_get, "/test2/t/e") == lnm_http_route_err_unknown_route); TEST_CHECK(lnm_http_router_route(NULL, router, lnm_http_method_head, "/test/test2") == lnm_http_route_err_unknown_method); TEST_CHECK(lnm_http_router_route(NULL, router, lnm_http_method_get, "/test/test2") == lnm_http_route_err_match); + + lnm_http_route_match match; + TEST_CHECK(lnm_http_router_route(&match, router, lnm_http_method_get, "/test/test_var") == lnm_http_route_err_match); + TEST_CHECK(match.key_segments[0].start == 6); + TEST_CHECK(match.key_segments[0].len == 8); + + TEST_CHECK(lnm_http_router_route(NULL, router, lnm_http_method_get, "/test/") == lnm_http_route_err_unknown_route); + + TEST_CHECK(lnm_http_router_route(&match, router, lnm_http_method_get, "/test/test_var/secondvar") == lnm_http_route_err_match); + TEST_CHECK(match.key_segments[0].start == 6); + TEST_CHECK(match.key_segments[0].len == 8); + TEST_CHECK(match.key_segments[1].start == 15); + TEST_CHECK(match.key_segments[1].len == 9); } TEST_LIST = { From 9dbdb0b089554165123d04560d6c7e0d2a763288 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Thu, 22 Feb 2024 22:31:00 +0100 Subject: [PATCH 06/21] feat(routing): add api to access key segments by name --- include/lnm/http/router.h | 13 +++++++++---- src/http/lnm_http_router.c | 27 +++++++++++++++++++++++++++ test/routing.c | 9 +++++++++ 3 files changed, 45 insertions(+), 4 deletions(-) diff --git a/include/lnm/http/router.h b/include/lnm/http/router.h index 9fbc05b..04956e4 100644 --- a/include/lnm/http/router.h +++ b/include/lnm/http/router.h @@ -8,13 +8,15 @@ typedef struct lnm_http_route lnm_http_route; +typedef struct lnm_http_route_match_segment { + size_t start; + size_t len; +} lnm_http_route_match_segment; + typedef struct lnm_http_route_match { const lnm_http_route *route; lnm_http_method method; - struct { - size_t start; - size_t len; - } key_segments[LNM_HTTP_MAX_KEY_SEGMENTS]; + lnm_http_route_match_segment key_segments[LNM_HTTP_MAX_KEY_SEGMENTS]; } lnm_http_route_match; typedef struct lnm_http_router lnm_http_router; @@ -47,4 +49,7 @@ lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, lnm_http_method method, const char *path); +lnm_err lnm_http_route_match_get(lnm_http_route_match_segment **out, + lnm_http_route_match *match, const char *key); + #endif diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index 6325deb..6f99431 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -268,3 +268,30 @@ lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, return __lnm_http_router_route(out, router, method, path, 0, 0); } + +lnm_err lnm_http_route_match_get(lnm_http_route_match_segment **out, + lnm_http_route_match *match, const char *key) { + if (match->route->key_segments == NULL) { + return lnm_err_not_found; + } + + lnm_http_route_segment_trie *trie = match->route->key_segments; + + while (*key != '\0') { + trie = trie->children[(unsigned char)*key]; + + if (trie == NULL) { + return lnm_err_not_found; + } + + key++; + } + + if (!trie->represents_segment) { + return lnm_err_not_found; + } + + *out = &match->key_segments[trie->index]; + + return lnm_err_ok; +} diff --git a/test/routing.c b/test/routing.c index a1d6a05..7cc7aea 100644 --- a/test/routing.c +++ b/test/routing.c @@ -28,6 +28,15 @@ void test_routing_simple() { TEST_CHECK(match.key_segments[0].len == 8); TEST_CHECK(match.key_segments[1].start == 15); TEST_CHECK(match.key_segments[1].len == 9); + + lnm_http_route_match_segment *segment; + TEST_CHECK(lnm_http_route_match_get(&segment, &match, "second") == lnm_err_ok); + TEST_CHECK(segment->start == 15); + TEST_CHECK(segment->len == 9); + TEST_CHECK(lnm_http_route_match_get(&segment, &match, "yuhh") == lnm_err_not_found); + TEST_CHECK(lnm_http_route_match_get(&segment, &match, "hello") == lnm_err_ok); + TEST_CHECK(segment->start == 6); + TEST_CHECK(segment->len == 8); } TEST_LIST = { From d739157fb17e2b92e5feab4e90e1dab7915b3e82 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Fri, 23 Feb 2024 11:38:52 +0100 Subject: [PATCH 07/21] refactor(routing): simply key segment api --- include/lnm/http/router.h | 4 ++-- src/http/lnm_http_router.c | 22 +++++++++------------- test/routing.c | 8 ++++---- 3 files changed, 15 insertions(+), 19 deletions(-) diff --git a/include/lnm/http/router.h b/include/lnm/http/router.h index 04956e4..f2ed321 100644 --- a/include/lnm/http/router.h +++ b/include/lnm/http/router.h @@ -49,7 +49,7 @@ lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, lnm_http_method method, const char *path); -lnm_err lnm_http_route_match_get(lnm_http_route_match_segment **out, - lnm_http_route_match *match, const char *key); +const lnm_http_route_match_segment * +lnm_http_route_match_get(lnm_http_route_match *match, const char *key); #endif diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index 6f99431..3dcc857 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -56,9 +56,7 @@ void lnm_http_route_segment_trie_free(lnm_http_route_segment_trie *trie) { } for (size_t i = 0; i < 128; i++) { - if (trie->children[i] != NULL) { - lnm_http_route_segment_trie_free(trie->children[i]); - } + lnm_http_route_segment_trie_free(trie->children[i]); } free(trie); @@ -94,8 +92,8 @@ lnm_err lnm_http_route_key_segment_insert(lnm_http_route *route, } static bool is_ascii(const char *s) { - while (*s != '0') { - if (*s > 127) { + while (*s != '\0') { + if (*s < 0) { return false; } @@ -269,10 +267,10 @@ lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, return __lnm_http_router_route(out, router, method, path, 0, 0); } -lnm_err lnm_http_route_match_get(lnm_http_route_match_segment **out, - lnm_http_route_match *match, const char *key) { +const lnm_http_route_match_segment * +lnm_http_route_match_get(lnm_http_route_match *match, const char *key) { if (match->route->key_segments == NULL) { - return lnm_err_not_found; + return NULL; } lnm_http_route_segment_trie *trie = match->route->key_segments; @@ -281,17 +279,15 @@ lnm_err lnm_http_route_match_get(lnm_http_route_match_segment **out, trie = trie->children[(unsigned char)*key]; if (trie == NULL) { - return lnm_err_not_found; + return NULL; } key++; } if (!trie->represents_segment) { - return lnm_err_not_found; + return NULL; } - *out = &match->key_segments[trie->index]; - - return lnm_err_ok; + return &match->key_segments[trie->index]; } diff --git a/test/routing.c b/test/routing.c index 7cc7aea..788caaa 100644 --- a/test/routing.c +++ b/test/routing.c @@ -29,12 +29,12 @@ void test_routing_simple() { TEST_CHECK(match.key_segments[1].start == 15); TEST_CHECK(match.key_segments[1].len == 9); - lnm_http_route_match_segment *segment; - TEST_CHECK(lnm_http_route_match_get(&segment, &match, "second") == lnm_err_ok); + const lnm_http_route_match_segment *segment; + TEST_CHECK((segment = lnm_http_route_match_get(&match, "second")) != NULL); TEST_CHECK(segment->start == 15); TEST_CHECK(segment->len == 9); - TEST_CHECK(lnm_http_route_match_get(&segment, &match, "yuhh") == lnm_err_not_found); - TEST_CHECK(lnm_http_route_match_get(&segment, &match, "hello") == lnm_err_ok); + TEST_CHECK((segment = lnm_http_route_match_get(&match, "yuhh")) == NULL); + TEST_CHECK((segment = lnm_http_route_match_get(&match, "hello")) != NULL); TEST_CHECK(segment->start == 6); TEST_CHECK(segment->len == 8); } From e29e02ff85365294047f7d83d9ca5fdaabbe1cde Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Fri, 23 Feb 2024 12:15:43 +0100 Subject: [PATCH 08/21] feat(routing): integrate new router into framework --- example/blocking.c | 12 ++- include/lnm/http/loop.h | 100 +++++++++++++----------- include/lnm/http/router.h | 55 ------------- src/_include/lnm/http/loop_internal.h | 54 +++++++------ src/_include/lnm/http/router_internal.h | 37 --------- src/http/lnm_http_loop.c | 89 +-------------------- src/http/lnm_http_loop_process.c | 55 +++---------- src/http/lnm_http_route.c | 94 ++++++++++++++++++++++ src/http/lnm_http_router.c | 69 +--------------- 9 files changed, 201 insertions(+), 364 deletions(-) delete mode 100644 include/lnm/http/router.h delete mode 100644 src/_include/lnm/http/router_internal.h create mode 100644 src/http/lnm_http_route.c diff --git a/example/blocking.c b/example/blocking.c index a145ed5..e4324e3 100644 --- a/example/blocking.c +++ b/example/blocking.c @@ -21,15 +21,19 @@ lnm_http_step_err slow_step(lnm_http_conn *conn) { int main() { lnm_http_loop *hl; lnm_http_step *step = NULL; - lnm_http_route *route; lnm_http_loop_init(&hl, NULL, ctx_init, ctx_reset, ctx_free); - lnm_http_step_append(&step, slow_step, true); - lnm_http_route_init_literal(&route, lnm_http_method_get, "/", step); - lnm_http_loop_route_add(hl, route); + lnm_http_router *router; + lnm_http_router_init(&router); + + lnm_http_route *route; + lnm_http_router_add(&route, router, lnm_http_method_get, "/"); + lnm_http_route_step_append(route, slow_step, true); + + lnm_http_loop_router_set(hl, router); lnm_log_init_global(); lnm_log_register_stdout(lnm_log_level_debug); diff --git a/include/lnm/http/loop.h b/include/lnm/http/loop.h index fefdf6a..892723a 100644 --- a/include/lnm/http/loop.h +++ b/include/lnm/http/loop.h @@ -7,6 +7,8 @@ #include "lnm/http/req.h" #include "lnm/http/res.h" +#define LNM_HTTP_MAX_KEY_SEGMENTS 4 + typedef enum lnm_http_step_err { lnm_http_step_err_done = 0, lnm_http_step_err_io_needed, @@ -22,6 +24,55 @@ typedef void (*lnm_http_ctx_reset_fn)(void *c_ctx); typedef void (*lnm_http_ctx_free_fn)(void *c_ctx); +typedef struct lnm_http_route lnm_http_route; + +typedef struct lnm_http_route_match_segment { + size_t start; + size_t len; +} lnm_http_route_match_segment; + +typedef struct lnm_http_route_match { + const lnm_http_route *route; + lnm_http_method method; + lnm_http_route_match_segment key_segments[LNM_HTTP_MAX_KEY_SEGMENTS]; +} lnm_http_route_match; + +typedef struct lnm_http_router lnm_http_router; + +typedef enum lnm_http_route_err { + lnm_http_route_err_match = 0, + lnm_http_route_err_unknown_route = 1, + lnm_http_route_err_unknown_method = 2, +} lnm_http_route_err; + +/** + * Allocate and initialize a new http_router. + */ +lnm_err lnm_http_router_init(lnm_http_router **out); + +void lnm_http_router_free(lnm_http_router *router); + +lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, + lnm_http_method method, const char *path); + +/** + * Add all of the child router's routes to the parent router, under the given + * route prefix. + */ +lnm_err lnm_http_router_nest(lnm_http_router *parent, + const lnm_http_router *child, const char *prefix); + +lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, + const lnm_http_router *router, + lnm_http_method method, + const char *path); + +const lnm_http_route_match_segment * +lnm_http_route_match_get(lnm_http_route_match *match, const char *key); + +lnm_err lnm_http_route_step_append(lnm_http_route *route, lnm_http_step_fn fn, + bool blocking); + /** * Initialize a new `lnm_http_loop`. * @@ -32,47 +83,7 @@ lnm_err lnm_http_loop_init(lnm_http_loop **out, void *c_gctx, lnm_http_ctx_reset_fn ctx_reset, lnm_http_ctx_free_fn ctx_free); -/** - * Append the given step fn to the step. - * - * @param out both the previous step to append the new step to, and the output - * variable to which the new step is appended - * @param fn step function - * @param blocking whether the step is blocking or not - */ -lnm_err lnm_http_step_append(lnm_http_step **out, lnm_http_step_fn fn, - bool blocking); - -/** - * Initialize a new route of type literal. - * - * @param out where to store pointer to new `lnm_http_route` - * @param path literal path to match - * @param step step to process request with - */ -lnm_err lnm_http_route_init_literal(lnm_http_route **out, - lnm_http_method method, const char *path, - lnm_http_step *step); - -/** - * Initialize a new route of type regex. - * - * @param out where to store pointer to new `lnm_http_route` - * @param pattern regex pattern - * @param regex_group_count how many regex groups are contained in the pattern - * @param step step to process request with - */ -lnm_err lnm_http_route_init_regex(lnm_http_route **out, lnm_http_method method, - const char *pattern, int regex_group_count, - lnm_http_step *step); - -/** - * Add a new route to the HTTP route. - * - * @param hl HTTP loop to modify - * @param route route to add - */ -lnm_err lnm_http_loop_route_add(lnm_http_loop *hl, lnm_http_route *route); +void lnm_http_loop_router_set(lnm_http_loop *hl, lnm_http_router *router); lnm_err lnm_http_loop_run(lnm_http_loop *hl, uint16_t port, size_t epoll_threads, size_t worker_threads); @@ -106,10 +117,7 @@ typedef enum lnm_http_loop_state { } lnm_http_loop_state; typedef struct lnm_http_loop_gctx { - struct { - lnm_http_route **arr; - size_t len; - } routes; + lnm_http_router *router; lnm_http_ctx_init_fn ctx_init; lnm_http_ctx_reset_fn ctx_reset; lnm_http_ctx_free_fn ctx_free; @@ -122,7 +130,7 @@ typedef struct lnm_http_loop_ctx { lnm_http_loop_state state; lnm_http_req req; lnm_http_res res; - lnm_http_route *route; + const lnm_http_route *route; lnm_http_step *cur_step; lnm_http_loop_gctx *g; void *c; diff --git a/include/lnm/http/router.h b/include/lnm/http/router.h deleted file mode 100644 index f2ed321..0000000 --- a/include/lnm/http/router.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef LNM_HTTP_ROUTER -#define LNM_HTTP_ROUTER - -#define LNM_HTTP_MAX_KEY_SEGMENTS 4 - -#include "lnm/common.h" -#include "lnm/http/consts.h" - -typedef struct lnm_http_route lnm_http_route; - -typedef struct lnm_http_route_match_segment { - size_t start; - size_t len; -} lnm_http_route_match_segment; - -typedef struct lnm_http_route_match { - const lnm_http_route *route; - lnm_http_method method; - lnm_http_route_match_segment key_segments[LNM_HTTP_MAX_KEY_SEGMENTS]; -} lnm_http_route_match; - -typedef struct lnm_http_router lnm_http_router; - -typedef enum lnm_http_route_err { - lnm_http_route_err_match = 0, - lnm_http_route_err_unknown_route = 1, - lnm_http_route_err_unknown_method = 2, -} lnm_http_route_err; - -/** - * Allocate and initialize a new http_router. - */ -lnm_err lnm_http_router_init(lnm_http_router **out); - -void lnm_http_router_free(lnm_http_router *router); - -lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, - lnm_http_method method, const char *path); - -/** - * Add all of the child router's routes to the parent router, under the given - * route prefix. - */ -lnm_err lnm_http_router_nest(lnm_http_router *parent, - const lnm_http_router *child, const char *prefix); - -lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, - const lnm_http_router *router, - lnm_http_method method, - const char *path); - -const lnm_http_route_match_segment * -lnm_http_route_match_get(lnm_http_route_match *match, const char *key); - -#endif diff --git a/src/_include/lnm/http/loop_internal.h b/src/_include/lnm/http/loop_internal.h index a343de6..2a8c0ec 100644 --- a/src/_include/lnm/http/loop_internal.h +++ b/src/_include/lnm/http/loop_internal.h @@ -5,42 +5,48 @@ #include "lnm/http/loop.h" +struct lnm_http_router { + struct lnm_http_router *exact_children[128]; + struct lnm_http_router *single_segment_child; + lnm_http_route *routes[lnm_http_method_total]; + bool represents_route; +}; + +typedef struct lnm_http_route_segment_trie { + struct lnm_http_route_segment_trie *children[128]; + size_t index; + bool represents_segment; +} lnm_http_route_segment_trie; + +lnm_err lnm_http_route_segment_trie_init(lnm_http_route_segment_trie **out); + +void lnm_http_route_segment_trie_free(lnm_http_route_segment_trie *trie); + +lnm_err lnm_http_route_key_segment_insert(lnm_http_route *route, + const char *key, size_t key_len, + size_t index); typedef struct lnm_http_step { lnm_http_step_fn fn; struct lnm_http_step *next; bool blocking; } lnm_http_step; -typedef enum lnm_http_route_type { - lnm_http_route_type_literal = 0, - lnm_http_route_type_regex, -} lnm_http_route_type; - -typedef struct lnm_http_route { - union { - regex_t *regex; - const char *s; - } route; - lnm_http_method method; - lnm_http_route_type type; - int regex_group_count; - lnm_http_step *step; -} lnm_http_route; - -/** - * Initialize a new empty route. - * - * @param out where to store pointer to new `lnm_http_route` - */ -lnm_err lnm_http_route_init(lnm_http_route **out); - /** * Initialize a first step. * * @param out where to store pointer to new `lnm_http_step` * @param fn step function associated with the step */ -lnm_err lnm_http_step_init(lnm_http_step **out, lnm_http_step_fn fn); +lnm_err lnm_http_step_init(lnm_http_step **out); + +struct lnm_http_route { + lnm_http_route_segment_trie *key_segments; + lnm_http_step *step; +}; + +lnm_err lnm_http_route_init(lnm_http_route **out); + +void lnm_http_route_free(lnm_http_route *route); /** * Initialize a new global context object. diff --git a/src/_include/lnm/http/router_internal.h b/src/_include/lnm/http/router_internal.h deleted file mode 100644 index 6c402d3..0000000 --- a/src/_include/lnm/http/router_internal.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef LNM_HTTP_ROUTER_INTERNAL -#define LNM_HTTP_ROUTER_INTERNAL - -#include "lnm/common.h" -#include "lnm/http/consts.h" -#include "lnm/http/router.h" - -typedef struct lnm_http_route_segment_trie { - struct lnm_http_route_segment_trie *children[128]; - size_t index; - bool represents_segment; -} lnm_http_route_segment_trie; - -lnm_err lnm_http_route_segment_trie_init(lnm_http_route_segment_trie **out); - -void lnm_http_route_segment_trie_free(lnm_http_route_segment_trie *trie); - -lnm_err lnm_http_route_key_segment_insert(lnm_http_route *route, - const char *key, size_t key_len, - size_t index); - -struct lnm_http_route { - lnm_http_route_segment_trie *key_segments; -}; - -struct lnm_http_router { - struct lnm_http_router *exact_children[128]; - struct lnm_http_router *single_segment_child; - lnm_http_route *routes[lnm_http_method_total]; - bool represents_route; -}; - -lnm_err lnm_http_route_init(lnm_http_route **out); - -void lnm_http_route_free(lnm_http_route *route); - -#endif diff --git a/src/http/lnm_http_loop.c b/src/http/lnm_http_loop.c index bd83526..7b31e80 100644 --- a/src/http/lnm_http_loop.c +++ b/src/http/lnm_http_loop.c @@ -28,94 +28,9 @@ lnm_err lnm_http_loop_init(lnm_http_loop **out, void *c_gctx, return lnm_err_ok; } -lnm_err lnm_http_step_append(lnm_http_step **out, lnm_http_step_fn fn, - bool blocking) { - lnm_http_step *step = calloc(1, sizeof(lnm_http_step)); - - if (step == NULL) { - return lnm_err_failed_alloc; - } - - step->fn = fn; - step->blocking = blocking; - - if ((*out) != NULL) { - (*out)->next = step; - } - - *out = step; - - return lnm_err_ok; -} - -lnm_err lnm_http_route_init(lnm_http_route **out) { - lnm_http_route *route = calloc(1, sizeof(lnm_http_route)); - - if (route == NULL) { - return lnm_err_failed_alloc; - } - - *out = route; - - return lnm_err_ok; -} - -lnm_err lnm_http_route_init_literal(lnm_http_route **out, - lnm_http_method method, const char *path, - lnm_http_step *step) { - LNM_RES(lnm_http_route_init(out)); - - (*out)->type = lnm_http_route_type_literal; - (*out)->method = method; - (*out)->route.s = path; - (*out)->step = step; - - return lnm_err_ok; -} - -lnm_err lnm_http_route_init_regex(lnm_http_route **out, lnm_http_method method, - const char *pattern, int regex_group_count, - lnm_http_step *step) { - regex_t *regex = calloc(1, sizeof(regex_t)); - - if (regex == NULL) { - return lnm_err_failed_alloc; - } - - if (regcomp(regex, pattern, REG_EXTENDED) != 0) { - free(regex); - return lnm_err_bad_regex; - } - - LNM_RES2(lnm_http_route_init(out), free(regex)); - - (*out)->method = method; - (*out)->type = lnm_http_route_type_regex; - (*out)->route.regex = regex; - (*out)->regex_group_count = regex_group_count; - (*out)->step = step; - - return lnm_err_ok; -} - -lnm_err lnm_http_loop_route_add(lnm_http_loop *hl, lnm_http_route *route) { +void lnm_http_loop_router_set(lnm_http_loop *hl, lnm_http_router *router) { lnm_http_loop_gctx *gctx = hl->gctx; - - lnm_http_route **new_routes = - gctx->routes.len > 0 - ? realloc(gctx->routes.arr, - (gctx->routes.len + 1) * sizeof(lnm_http_route *)) - : malloc(sizeof(lnm_http_route *)); - - if (new_routes == NULL) { - return lnm_err_failed_alloc; - } - - new_routes[gctx->routes.len] = route; - gctx->routes.arr = new_routes; - gctx->routes.len++; - - return lnm_err_ok; + gctx->router = router; } lnm_err lnm_http_loop_run(lnm_http_loop *hl, uint16_t port, diff --git a/src/http/lnm_http_loop_process.c b/src/http/lnm_http_loop_process.c index 1e465cf..e6a405e 100644 --- a/src/http/lnm_http_loop_process.c +++ b/src/http/lnm_http_loop_process.c @@ -56,55 +56,24 @@ void lnm_http_loop_process_parse_req(lnm_http_conn *conn) { void lnm_http_loop_process_route(lnm_http_conn *conn) { lnm_http_loop_ctx *ctx = conn->ctx; - lnm_http_loop_gctx *gctx = ctx->g; + const lnm_http_loop_gctx *gctx = ctx->g; - // 0: no match - // 1: matched route, but not method - // 2: fully matched route - int match_level = 0; - lnm_http_route *route; + lnm_http_route_match match; - for (size_t i = 0; i < gctx->routes.len && match_level < 3; i++) { - route = gctx->routes.arr[i]; - bool matched_path = false; - - switch (route->type) { - case lnm_http_route_type_literal: - matched_path = strncmp(route->route.s, ctx->req.buf.s + ctx->req.path.o, - ctx->req.path.len) == 0; - break; - case lnm_http_route_type_regex: - matched_path = - regexec(route->route.regex, ctx->req.buf.s + ctx->req.path.o, - LNM_HTTP_MAX_REGEX_GROUPS, ctx->req.path.groups, 0) == 0; - break; - } - - // GET routes also automatically route HEAD requests - bool matched_method = route->method == ctx->req.method || - (route->method == lnm_http_method_get && - ctx->req.method == lnm_http_method_head); - int new_match_level = 2 * matched_path + matched_method; - - // Remember the previous match levels so we can return the correct status - // message - match_level = match_level < new_match_level ? new_match_level : match_level; - } - - switch (match_level) { - case 0: - case 1: - ctx->res.status = lnm_http_status_not_found; - ctx->state = lnm_http_loop_state_first_res; + switch (lnm_http_router_route(&match, gctx->router, ctx->req.method, + ctx->req.buf.s + ctx->req.path.o)) { + case lnm_http_route_err_match: + ctx->route = match.route; + ctx->cur_step = match.route->step; + ctx->state = lnm_http_loop_state_parse_headers; break; - case 2: + case lnm_http_route_err_unknown_method: ctx->res.status = lnm_http_status_method_not_allowed; ctx->state = lnm_http_loop_state_first_res; break; - case 3: - ctx->route = route; - ctx->cur_step = route->step; - ctx->state = lnm_http_loop_state_parse_headers; + case lnm_http_route_err_unknown_route: + ctx->res.status = lnm_http_status_not_found; + ctx->state = lnm_http_loop_state_first_res; break; } } diff --git a/src/http/lnm_http_route.c b/src/http/lnm_http_route.c new file mode 100644 index 0000000..231a89d --- /dev/null +++ b/src/http/lnm_http_route.c @@ -0,0 +1,94 @@ +#include "lnm/http/loop_internal.h" + +lnm_err lnm_http_route_init(lnm_http_route **out) { + lnm_http_route *route = calloc(1, sizeof(lnm_http_route)); + + if (route == NULL) { + return lnm_err_failed_alloc; + } + + *out = route; + + return lnm_err_ok; +} + +lnm_err lnm_http_route_segment_trie_init(lnm_http_route_segment_trie **out) { + lnm_http_route_segment_trie *trie = + calloc(1, sizeof(lnm_http_route_segment_trie)); + + if (trie == NULL) { + return lnm_err_failed_alloc; + } + + *out = trie; + + return lnm_err_ok; +} + +void lnm_http_route_segment_trie_free(lnm_http_route_segment_trie *trie) { + if (trie == NULL) { + return; + } + + for (size_t i = 0; i < 128; i++) { + lnm_http_route_segment_trie_free(trie->children[i]); + } + + free(trie); +} + +lnm_err lnm_http_route_key_segment_insert(lnm_http_route *route, + const char *key, size_t key_len, + size_t index) { + if (route->key_segments == NULL) { + LNM_RES(lnm_http_route_segment_trie_init(&route->key_segments)); + } + + lnm_http_route_segment_trie *trie = route->key_segments; + + for (size_t key_index = 0; key_index < key_len; key_index++) { + unsigned char c = key[key_index]; + + if (trie->children[c] == NULL) { + LNM_RES(lnm_http_route_segment_trie_init(&trie->children[c])); + } + + trie = trie->children[c]; + } + + if (trie->represents_segment) { + return lnm_err_already_present; + } + + trie->represents_segment = true; + trie->index = index; + + return lnm_err_ok; +} + +lnm_err lnm_http_step_init(lnm_http_step **out) { + lnm_http_step *step = calloc(1, sizeof(lnm_http_step)); + + if (step == NULL) { + return lnm_err_failed_alloc; + } + + *out = step; + + return lnm_err_ok; +} + +lnm_err lnm_http_route_step_append(lnm_http_route *route, lnm_http_step_fn fn, + bool blocking) { + lnm_http_step **step_ptr = &route->step; + + while (*step_ptr != NULL) { + step_ptr = &(*step_ptr)->next; + } + + LNM_RES(lnm_http_step_init(step_ptr)); + (*step_ptr)->fn = fn; + (*step_ptr)->blocking = blocking; + + return lnm_err_ok; +} diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index 3dcc857..dddf882 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -1,8 +1,7 @@ #include #include "lnm/common.h" -#include "lnm/http/router.h" -#include "lnm/http/router_internal.h" +#include "lnm/http/loop_internal.h" lnm_err lnm_http_router_init(lnm_http_router **out) { lnm_http_router *router = calloc(1, sizeof(lnm_http_router)); @@ -16,18 +15,6 @@ lnm_err lnm_http_router_init(lnm_http_router **out) { return lnm_err_ok; } -lnm_err lnm_http_route_init(lnm_http_route **out) { - lnm_http_route *route = calloc(1, sizeof(lnm_http_route)); - - if (route == NULL) { - return lnm_err_failed_alloc; - } - - *out = route; - - return lnm_err_ok; -} - void lnm_http_route_free(lnm_http_route *route) { if (route == NULL) { return; @@ -37,60 +24,6 @@ void lnm_http_route_free(lnm_http_route *route) { free(route); } -lnm_err lnm_http_route_segment_trie_init(lnm_http_route_segment_trie **out) { - lnm_http_route_segment_trie *trie = - calloc(1, sizeof(lnm_http_route_segment_trie)); - - if (trie == NULL) { - return lnm_err_failed_alloc; - } - - *out = trie; - - return lnm_err_ok; -} - -void lnm_http_route_segment_trie_free(lnm_http_route_segment_trie *trie) { - if (trie == NULL) { - return; - } - - for (size_t i = 0; i < 128; i++) { - lnm_http_route_segment_trie_free(trie->children[i]); - } - - free(trie); -} - -lnm_err lnm_http_route_key_segment_insert(lnm_http_route *route, - const char *key, size_t key_len, - size_t index) { - if (route->key_segments == NULL) { - LNM_RES(lnm_http_route_segment_trie_init(&route->key_segments)); - } - - lnm_http_route_segment_trie *trie = route->key_segments; - - for (size_t key_index = 0; key_index < key_len; key_index++) { - unsigned char c = key[key_index]; - - if (trie->children[c] == NULL) { - LNM_RES(lnm_http_route_segment_trie_init(&trie->children[c])); - } - - trie = trie->children[c]; - } - - if (trie->represents_segment) { - return lnm_err_already_present; - } - - trie->represents_segment = true; - trie->index = index; - - return lnm_err_ok; -} - static bool is_ascii(const char *s) { while (*s != '\0') { if (*s < 0) { From 9fa009ccf4d308aeca3323c151d26e6edcb41769 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Fri, 23 Feb 2024 15:21:23 +0100 Subject: [PATCH 09/21] feat: provide access to key segments from step --- example/routing.c | 44 ++++++++++++++++++++++++++++++++ include/lnm/http/loop.h | 2 +- src/http/lnm_http_loop_ctx.c | 1 - src/http/lnm_http_loop_process.c | 7 ++--- src/http/lnm_http_router.c | 6 ++--- test/routing.c | 2 +- 6 files changed, 51 insertions(+), 11 deletions(-) create mode 100644 example/routing.c diff --git a/example/routing.c b/example/routing.c new file mode 100644 index 0000000..47d02b3 --- /dev/null +++ b/example/routing.c @@ -0,0 +1,44 @@ +#include + +#include "lnm/log.h" +#include "lnm/loop.h" +#include "lnm/http/loop.h" + +lnm_err ctx_init(void **c_ctx, void *gctx) { + *c_ctx = NULL; + + return lnm_err_ok; +} + +void ctx_reset(void *c_ctx) {} +void ctx_free(void *c_ctx) {} + +lnm_http_step_err print_step(lnm_http_conn *conn) { + lnm_http_loop_ctx *ctx = conn->ctx; + + const lnm_http_route_match_segment *seg = lnm_http_route_match_get(&ctx->match, "key"); + lnm_linfo("main", "key: %.*s", seg->len, ctx->req.buf.s + ctx->req.path.o + seg->start); + return lnm_http_step_err_done; +} + +int main() { + lnm_http_loop *hl; + + lnm_http_loop_init(&hl, NULL, ctx_init, + ctx_reset, + ctx_free); + + lnm_http_router *router; + lnm_http_router_init(&router); + + lnm_http_route *route; + lnm_http_router_add(&route, router, lnm_http_method_get, "/:key"); + lnm_http_route_step_append(route, print_step, false); + + lnm_http_loop_router_set(hl, router); + + lnm_log_init_global(); + lnm_log_register_stdout(lnm_log_level_debug); + + printf("res = %i\n", lnm_http_loop_run(hl, 8080, 1, 0)); +} diff --git a/include/lnm/http/loop.h b/include/lnm/http/loop.h index 892723a..3731f34 100644 --- a/include/lnm/http/loop.h +++ b/include/lnm/http/loop.h @@ -130,7 +130,7 @@ typedef struct lnm_http_loop_ctx { lnm_http_loop_state state; lnm_http_req req; lnm_http_res res; - const lnm_http_route *route; + lnm_http_route_match match; lnm_http_step *cur_step; lnm_http_loop_gctx *g; void *c; diff --git a/src/http/lnm_http_loop_ctx.c b/src/http/lnm_http_loop_ctx.c index 87741e2..848fe86 100644 --- a/src/http/lnm_http_loop_ctx.c +++ b/src/http/lnm_http_loop_ctx.c @@ -42,7 +42,6 @@ void lnm_http_loop_ctx_reset(lnm_http_loop_ctx *ctx) { lnm_http_req_reset(&ctx->req); lnm_http_res_reset(&ctx->res); - ctx->route = NULL; ctx->cur_step = NULL; } diff --git a/src/http/lnm_http_loop_process.c b/src/http/lnm_http_loop_process.c index e6a405e..91b9254 100644 --- a/src/http/lnm_http_loop_process.c +++ b/src/http/lnm_http_loop_process.c @@ -58,13 +58,10 @@ void lnm_http_loop_process_route(lnm_http_conn *conn) { lnm_http_loop_ctx *ctx = conn->ctx; const lnm_http_loop_gctx *gctx = ctx->g; - lnm_http_route_match match; - - switch (lnm_http_router_route(&match, gctx->router, ctx->req.method, + switch (lnm_http_router_route(&ctx->match, gctx->router, ctx->req.method, ctx->req.buf.s + ctx->req.path.o)) { case lnm_http_route_err_match: - ctx->route = match.route; - ctx->cur_step = match.route->step; + ctx->cur_step = ctx->match.route->step; ctx->state = lnm_http_loop_state_parse_headers; break; case lnm_http_route_err_unknown_method: diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index dddf882..8b071db 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -53,10 +53,10 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, switch (c) { case ':': { - const char *next_slash_ptr = strchr(path, '/'); + const char *next_slash_ptr = strchr(path + 1, '/'); const char *new_path = - next_slash_ptr == NULL ? strchr(path, '\0') : next_slash_ptr; - size_t key_len = new_path - path - 1; + next_slash_ptr == NULL ? strchr(path + 1, '\0') : next_slash_ptr; + size_t key_len = new_path - (path + 1); if (key_len == 0) { res = lnm_err_invalid_route; diff --git a/test/routing.c b/test/routing.c index 788caaa..f21dbdb 100644 --- a/test/routing.c +++ b/test/routing.c @@ -1,6 +1,6 @@ #include "test.h" -#include "lnm/http/router.h" +#include "lnm/http/loop.h" void test_routing_simple() { lnm_http_router *router; From fbd41f7e4eaa303c799084f889bce59d90de8c41 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Sat, 24 Feb 2024 13:25:06 +0100 Subject: [PATCH 10/21] feat: implement router free function --- src/http/lnm_http_route.c | 9 +++++++++ src/http/lnm_http_router.c | 17 +++++++++++++---- test/routing.c | 4 +++- 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/http/lnm_http_route.c b/src/http/lnm_http_route.c index 231a89d..9901b79 100644 --- a/src/http/lnm_http_route.c +++ b/src/http/lnm_http_route.c @@ -12,6 +12,15 @@ lnm_err lnm_http_route_init(lnm_http_route **out) { return lnm_err_ok; } +void lnm_http_route_free(lnm_http_route *route) { + if (route == NULL) { + return; + } + + lnm_http_route_segment_trie_free(route->key_segments); + free(route); +} + lnm_err lnm_http_route_segment_trie_init(lnm_http_route_segment_trie **out) { lnm_http_route_segment_trie *trie = calloc(1, sizeof(lnm_http_route_segment_trie)); diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index 8b071db..e735e02 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -15,13 +15,22 @@ lnm_err lnm_http_router_init(lnm_http_router **out) { return lnm_err_ok; } -void lnm_http_route_free(lnm_http_route *route) { - if (route == NULL) { +void lnm_http_router_free(lnm_http_router *router) { + if (router == NULL) { return; } - lnm_http_route_segment_trie_free(route->key_segments); - free(route); + for (size_t i = 0; i < 128; i++) { + lnm_http_router_free(router->exact_children[i]); + } + + lnm_http_router_free(router->single_segment_child); + + for (size_t i = 0; i < lnm_http_method_total; i++) { + lnm_http_route_free(router->routes[i]); + } + + free(router); } static bool is_ascii(const char *s) { diff --git a/test/routing.c b/test/routing.c index f21dbdb..e18b695 100644 --- a/test/routing.c +++ b/test/routing.c @@ -4,7 +4,7 @@ void test_routing_simple() { lnm_http_router *router; - lnm_http_router_init(&router); + TEST_CHECK(lnm_http_router_init(&router) == lnm_err_ok); TEST_CHECK(lnm_http_router_add(NULL, router, lnm_http_method_get, "/test") == lnm_err_ok); TEST_CHECK(lnm_http_router_add(NULL, router, lnm_http_method_get, "/test/test2") == lnm_err_ok); @@ -37,6 +37,8 @@ void test_routing_simple() { TEST_CHECK((segment = lnm_http_route_match_get(&match, "hello")) != NULL); TEST_CHECK(segment->start == 6); TEST_CHECK(segment->len == 8); + + lnm_http_router_free(router); } TEST_LIST = { From 3ae1b62dd0a25dfb57bb3fc7694b75f60888fed5 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Sun, 25 Feb 2024 21:50:51 +0100 Subject: [PATCH 11/21] feat(routing): make path segments easily accessible from request struct --- example/routing.c | 6 ++- include/lnm/http/loop.h | 62 +--------------------------- include/lnm/http/req.h | 12 ++++++ include/lnm/http/route.h | 69 ++++++++++++++++++++++++++++++++ src/http/lnm_http_loop_process.c | 5 ++- src/http/lnm_http_req.c | 16 ++++++++ 6 files changed, 105 insertions(+), 65 deletions(-) create mode 100644 include/lnm/http/route.h diff --git a/example/routing.c b/example/routing.c index 47d02b3..19d64e1 100644 --- a/example/routing.c +++ b/example/routing.c @@ -1,5 +1,6 @@ #include +#include "lnm/http/req.h" #include "lnm/log.h" #include "lnm/loop.h" #include "lnm/http/loop.h" @@ -16,8 +17,9 @@ void ctx_free(void *c_ctx) {} lnm_http_step_err print_step(lnm_http_conn *conn) { lnm_http_loop_ctx *ctx = conn->ctx; - const lnm_http_route_match_segment *seg = lnm_http_route_match_get(&ctx->match, "key"); - lnm_linfo("main", "key: %.*s", seg->len, ctx->req.buf.s + ctx->req.path.o + seg->start); + const char *key; + size_t key_len = lnm_http_req_route_segment(&key, &ctx->req, "key") ; + lnm_linfo("main", "key: %.*s", key_len, key); return lnm_http_step_err_done; } diff --git a/include/lnm/http/loop.h b/include/lnm/http/loop.h index 3731f34..ba4337b 100644 --- a/include/lnm/http/loop.h +++ b/include/lnm/http/loop.h @@ -6,17 +6,7 @@ #include "lnm/common.h" #include "lnm/http/req.h" #include "lnm/http/res.h" - -#define LNM_HTTP_MAX_KEY_SEGMENTS 4 - -typedef enum lnm_http_step_err { - lnm_http_step_err_done = 0, - lnm_http_step_err_io_needed, - lnm_http_step_err_close, - lnm_http_step_err_res, -} lnm_http_step_err; - -typedef lnm_http_step_err (*lnm_http_step_fn)(lnm_http_conn *conn); +#include "lnm/http/route.h" typedef lnm_err (*lnm_http_ctx_init_fn)(void **c_ctx, void *gctx); @@ -24,55 +14,6 @@ typedef void (*lnm_http_ctx_reset_fn)(void *c_ctx); typedef void (*lnm_http_ctx_free_fn)(void *c_ctx); -typedef struct lnm_http_route lnm_http_route; - -typedef struct lnm_http_route_match_segment { - size_t start; - size_t len; -} lnm_http_route_match_segment; - -typedef struct lnm_http_route_match { - const lnm_http_route *route; - lnm_http_method method; - lnm_http_route_match_segment key_segments[LNM_HTTP_MAX_KEY_SEGMENTS]; -} lnm_http_route_match; - -typedef struct lnm_http_router lnm_http_router; - -typedef enum lnm_http_route_err { - lnm_http_route_err_match = 0, - lnm_http_route_err_unknown_route = 1, - lnm_http_route_err_unknown_method = 2, -} lnm_http_route_err; - -/** - * Allocate and initialize a new http_router. - */ -lnm_err lnm_http_router_init(lnm_http_router **out); - -void lnm_http_router_free(lnm_http_router *router); - -lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, - lnm_http_method method, const char *path); - -/** - * Add all of the child router's routes to the parent router, under the given - * route prefix. - */ -lnm_err lnm_http_router_nest(lnm_http_router *parent, - const lnm_http_router *child, const char *prefix); - -lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, - const lnm_http_router *router, - lnm_http_method method, - const char *path); - -const lnm_http_route_match_segment * -lnm_http_route_match_get(lnm_http_route_match *match, const char *key); - -lnm_err lnm_http_route_step_append(lnm_http_route *route, lnm_http_step_fn fn, - bool blocking); - /** * Initialize a new `lnm_http_loop`. * @@ -130,7 +71,6 @@ typedef struct lnm_http_loop_ctx { lnm_http_loop_state state; lnm_http_req req; lnm_http_res res; - lnm_http_route_match match; lnm_http_step *cur_step; lnm_http_loop_gctx *g; void *c; diff --git a/include/lnm/http/req.h b/include/lnm/http/req.h index 06f2743..1c32972 100644 --- a/include/lnm/http/req.h +++ b/include/lnm/http/req.h @@ -9,6 +9,7 @@ #include "lnm/common.h" #include "lnm/http/consts.h" +#include "lnm/http/route.h" #define LNM_HTTP_MAX_REQ_HEADERS 32 #define LNM_HTTP_MAX_REGEX_GROUPS 4 @@ -35,6 +36,7 @@ typedef struct lnm_http_req { } buf; int minor_version; lnm_http_method method; + lnm_http_route_match route_match; struct { size_t o; size_t len; @@ -108,4 +110,14 @@ lnm_err lnm_http_req_header_get(const char **out, size_t *out_len, lnm_err lnm_http_req_header_get_s(const char **out, size_t *out_len, lnm_http_req *req, const char *name); +/** + * Retrieve a named key segment from the matched route. + * + * @param out where to write pointer to string + * @param key key of the segment + * @return length of the outputted char buffer, or 0 if the key doesn't exist + */ +size_t lnm_http_req_route_segment(const char **out, lnm_http_req *req, + const char *key); + #endif diff --git a/include/lnm/http/route.h b/include/lnm/http/route.h new file mode 100644 index 0000000..f121b96 --- /dev/null +++ b/include/lnm/http/route.h @@ -0,0 +1,69 @@ +#ifndef LNM_HTTP_ROUTE +#define LNM_HTTP_ROUTE + +#include + +#include "lnm/common.h" +#include "lnm/http/consts.h" + +#define LNM_HTTP_MAX_KEY_SEGMENTS 4 + +typedef enum lnm_http_step_err { + lnm_http_step_err_done = 0, + lnm_http_step_err_io_needed, + lnm_http_step_err_close, + lnm_http_step_err_res, +} lnm_http_step_err; + +typedef lnm_http_step_err (*lnm_http_step_fn)(lnm_http_conn *conn); + +typedef struct lnm_http_route lnm_http_route; + +typedef struct lnm_http_route_match_segment { + size_t start; + size_t len; +} lnm_http_route_match_segment; + +typedef struct lnm_http_route_match { + const lnm_http_route *route; + lnm_http_method method; + lnm_http_route_match_segment key_segments[LNM_HTTP_MAX_KEY_SEGMENTS]; +} lnm_http_route_match; + +typedef struct lnm_http_router lnm_http_router; + +typedef enum lnm_http_route_err { + lnm_http_route_err_match = 0, + lnm_http_route_err_unknown_route = 1, + lnm_http_route_err_unknown_method = 2, +} lnm_http_route_err; + +/** + * Allocate and initialize a new http_router. + */ +lnm_err lnm_http_router_init(lnm_http_router **out); + +void lnm_http_router_free(lnm_http_router *router); + +lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, + lnm_http_method method, const char *path); + +/** + * Add all of the child router's routes to the parent router, under the given + * route prefix. + */ +lnm_err lnm_http_router_nest(lnm_http_router *parent, + const lnm_http_router *child, const char *prefix); + +lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, + const lnm_http_router *router, + lnm_http_method method, + const char *path); + +const lnm_http_route_match_segment * +lnm_http_route_match_get(lnm_http_route_match *match, const char *key); + +lnm_err lnm_http_route_step_append(lnm_http_route *route, lnm_http_step_fn fn, + bool blocking); + +#endif diff --git a/src/http/lnm_http_loop_process.c b/src/http/lnm_http_loop_process.c index 91b9254..ea690ce 100644 --- a/src/http/lnm_http_loop_process.c +++ b/src/http/lnm_http_loop_process.c @@ -58,10 +58,11 @@ void lnm_http_loop_process_route(lnm_http_conn *conn) { lnm_http_loop_ctx *ctx = conn->ctx; const lnm_http_loop_gctx *gctx = ctx->g; - switch (lnm_http_router_route(&ctx->match, gctx->router, ctx->req.method, + switch (lnm_http_router_route(&ctx->req.route_match, gctx->router, + ctx->req.method, ctx->req.buf.s + ctx->req.path.o)) { case lnm_http_route_err_match: - ctx->cur_step = ctx->match.route->step; + ctx->cur_step = ctx->req.route_match.route->step; ctx->state = lnm_http_loop_state_parse_headers; break; case lnm_http_route_err_unknown_method: diff --git a/src/http/lnm_http_req.c b/src/http/lnm_http_req.c index 50be3af..a612b02 100644 --- a/src/http/lnm_http_req.c +++ b/src/http/lnm_http_req.c @@ -112,3 +112,19 @@ lnm_err lnm_http_req_header_get_s(const char **out, size_t *out_len, return lnm_err_not_found; } + +size_t lnm_http_req_route_segment(const char **out, lnm_http_req *req, + const char *key) { + const lnm_http_route_match_segment *segment = + lnm_http_route_match_get(&req->route_match, key); + + if (segment == NULL) { + return 0; + } + + if (out != NULL) { + *out = req->buf.s + req->path.o + segment->start; + } + + return segment->len; +} From 115bf74456ea358eb77cb91b5148351b5d950a39 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Sun, 25 Feb 2024 22:59:58 +0100 Subject: [PATCH 12/21] feat(routing): multi-segment wildcard matches --- example/routing.c | 24 +++++++++++ src/_include/lnm/http/loop_internal.h | 25 +++++------ src/http/lnm_http_router.c | 60 +++++++++++++++++++++++++-- 3 files changed, 94 insertions(+), 15 deletions(-) diff --git a/example/routing.c b/example/routing.c index 19d64e1..e9ac1b1 100644 --- a/example/routing.c +++ b/example/routing.c @@ -23,6 +23,25 @@ lnm_http_step_err print_step(lnm_http_conn *conn) { return lnm_http_step_err_done; } +lnm_http_step_err print_step2(lnm_http_conn *conn) { + lnm_http_loop_ctx *ctx = conn->ctx; + + const char *key; + size_t key_len = lnm_http_req_route_segment(&key, &ctx->req, "key") ; + lnm_linfo("main", "yuhh key: %.*s", key_len, key); + return lnm_http_step_err_done; +} + +lnm_http_step_err print_step3(lnm_http_conn *conn) { + lnm_http_loop_ctx *ctx = conn->ctx; + + const char *key; + size_t key_len = lnm_http_req_route_segment(&key, &ctx->req, "cool") ; + lnm_linfo("main", "cool: %.*s", key_len, key); + return lnm_http_step_err_done; +} + + int main() { lnm_http_loop *hl; @@ -34,8 +53,13 @@ int main() { lnm_http_router_init(&router); lnm_http_route *route; + lnm_http_router_add(&route, router, lnm_http_method_get, "/emma"); lnm_http_router_add(&route, router, lnm_http_method_get, "/:key"); lnm_http_route_step_append(route, print_step, false); + lnm_http_router_add(&route, router, lnm_http_method_get, "/:key/two"); + lnm_http_route_step_append(route, print_step2, false); + lnm_http_router_add(&route, router, lnm_http_method_get, "/*cool"); + lnm_http_route_step_append(route, print_step3, false); lnm_http_loop_router_set(hl, router); diff --git a/src/_include/lnm/http/loop_internal.h b/src/_include/lnm/http/loop_internal.h index 2a8c0ec..d5cd510 100644 --- a/src/_include/lnm/http/loop_internal.h +++ b/src/_include/lnm/http/loop_internal.h @@ -5,19 +5,25 @@ #include "lnm/http/loop.h" -struct lnm_http_router { - struct lnm_http_router *exact_children[128]; - struct lnm_http_router *single_segment_child; - lnm_http_route *routes[lnm_http_method_total]; - bool represents_route; -}; - typedef struct lnm_http_route_segment_trie { struct lnm_http_route_segment_trie *children[128]; size_t index; bool represents_segment; } lnm_http_route_segment_trie; +struct lnm_http_route { + lnm_http_route_segment_trie *key_segments; + lnm_http_step *step; +}; + +struct lnm_http_router { + struct lnm_http_router *exact_children[128]; + struct lnm_http_router *single_segment_child; + lnm_http_route *multi_segment_routes[lnm_http_method_total]; + lnm_http_route *routes[lnm_http_method_total]; + bool represents_route; +}; + lnm_err lnm_http_route_segment_trie_init(lnm_http_route_segment_trie **out); void lnm_http_route_segment_trie_free(lnm_http_route_segment_trie *trie); @@ -39,11 +45,6 @@ typedef struct lnm_http_step { */ lnm_err lnm_http_step_init(lnm_http_step **out); -struct lnm_http_route { - lnm_http_route_segment_trie *key_segments; - lnm_http_step *step; -}; - lnm_err lnm_http_route_init(lnm_http_route **out); void lnm_http_route_free(lnm_http_route *route); diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index e735e02..ce15d9a 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -93,9 +93,42 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, http_router = http_router->single_segment_child; path = new_path; } break; - case '*': - // TODO multi-segment wildcard - break; + case '*': { + const char *next_slash_ptr = strchr(path + 1, '/'); + + // Star match should be at end of route + if (next_slash_ptr != NULL) { + res = lnm_err_invalid_route; + + goto end; + } + + const char *end = strchr(path + 1, '\0'); + size_t key_len = end - (path + 1); + + if (key_len == 0) { + res = lnm_err_invalid_route; + + goto end; + } + + res = lnm_http_route_key_segment_insert(route, path + 1, key_len, + key_segments_count); + + if (res != lnm_err_ok) { + goto end; + } + + key_segments_count++; + + if (http_router->multi_segment_routes[method] != NULL) { + res = lnm_err_overlapping_route; + } + + http_router->multi_segment_routes[method] = route; + goto end; + + } break; default: if (http_router->exact_children[c] == NULL) { res = lnm_http_router_init(&http_router->exact_children[c]); @@ -107,6 +140,7 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, http_router = http_router->exact_children[c]; path++; + break; } } @@ -195,6 +229,26 @@ static lnm_http_route_err __lnm_http_router_route(lnm_http_route_match *out, } } + const lnm_http_route *multi_segment_route = + router->multi_segment_routes[method]; + + if (multi_segment_route != NULL) { + const char *end_ptr = strchr(path + path_index, '\0'); + size_t segment_len = end_ptr - (path + path_index); + + // TODO do 405's make sense for star matches? + + if (segment_len > 0) { + if (out != NULL) { + out->route = multi_segment_route; + out->key_segments[matched_key_segments].start = path_index; + out->key_segments[matched_key_segments].len = segment_len; + } + + return lnm_http_route_err_match; + } + } + return res; } From 6eb965adcd90f80fefae53b8c07919ad22d87c20 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Mon, 26 Feb 2024 22:32:50 +0100 Subject: [PATCH 13/21] test(routing): add star matching test --- test/routing.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/test/routing.c b/test/routing.c index e18b695..e133f4b 100644 --- a/test/routing.c +++ b/test/routing.c @@ -41,7 +41,20 @@ void test_routing_simple() { lnm_http_router_free(router); } +void test_routing_star() { + lnm_http_router *router; + TEST_CHECK(lnm_http_router_init(&router) == lnm_err_ok); + + TEST_CHECK(lnm_http_router_add(NULL, router, lnm_http_method_get, "/*key") == lnm_err_ok); + + lnm_http_route_match match; + TEST_CHECK(lnm_http_router_route(&match, router, lnm_http_method_get, "/hello/world") == lnm_http_route_err_match); + TEST_CHECK(match.key_segments[0].start == 1); + TEST_CHECK(match.key_segments[0].len == 11); +} + TEST_LIST = { { "routing simple", test_routing_simple }, + { "routing star", test_routing_star }, { NULL, NULL } }; From 2ce49a3347aba6ba77c00b81e3f74ceb8ecfe33f Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Sat, 2 Mar 2024 11:11:54 +0100 Subject: [PATCH 14/21] feat(routing): implement router merging --- include/lnm/http/route.h | 20 ++++-- src/http/lnm_http_router.c | 143 +++++++++++++++++++++++++++++++++++++ test/routing.c | 49 +++++++++++++ 3 files changed, 208 insertions(+), 4 deletions(-) diff --git a/include/lnm/http/route.h b/include/lnm/http/route.h index f121b96..2d87a1b 100644 --- a/include/lnm/http/route.h +++ b/include/lnm/http/route.h @@ -49,11 +49,23 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, lnm_http_method method, const char *path); /** - * Add all of the child router's routes to the parent router, under the given - * route prefix. + * Checks whether the two routers have any conflicting parts. */ -lnm_err lnm_http_router_nest(lnm_http_router *parent, - const lnm_http_router *child, const char *prefix); +bool lnm_http_router_conflicts(const lnm_http_router *r1, + const lnm_http_router *r2); + +/** + * Merge two routers, with the result ending up in r1. This is equivalent to + * nesting a router on '/'. + */ +lnm_err lnm_http_router_merge(lnm_http_router *r1, lnm_http_router *r2); + +/** + * Integrate the child router into the parent routing, mounting its paths on the + * given prefix. + */ +lnm_err lnm_http_router_nest(lnm_http_router *parent, lnm_http_router *child, + const char *prefix); lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, const lnm_http_router *router, diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index ce15d9a..552369c 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -28,6 +28,7 @@ void lnm_http_router_free(lnm_http_router *router) { for (size_t i = 0; i < lnm_http_method_total; i++) { lnm_http_route_free(router->routes[i]); + lnm_http_route_free(router->multi_segment_routes[i]); } free(router); @@ -287,3 +288,145 @@ lnm_http_route_match_get(lnm_http_route_match *match, const char *key) { return &match->key_segments[trie->index]; } + +bool lnm_http_router_conflicts(const lnm_http_router *r1, + const lnm_http_router *r2) { + // First check the literal routes for the routers + for (lnm_http_method m = 0; m < lnm_http_method_total; m++) { + if ((r1->routes[m] != NULL && r2->routes[m] != NULL) || + (r1->multi_segment_routes[m] != NULL && + r2->multi_segment_routes[m] != NULL)) { + return true; + } + } + + if ((r1->single_segment_child != NULL && r2->single_segment_child != NULL) && + lnm_http_router_conflicts(r1->single_segment_child, + r2->single_segment_child)) { + return true; + } + + for (unsigned char c = 0; c < 128; c++) { + if ((r1->exact_children[c] != NULL && r2->exact_children[c] != NULL) && + lnm_http_router_conflicts(r1->exact_children[c], + r2->exact_children[c])) { + return true; + } + } + + return false; +} + +void __lnm_http_router_merge(lnm_http_router *r1, lnm_http_router *r2) { + for (lnm_http_method m = 0; m < lnm_http_method_total; m++) { + if (r2->routes[m] != NULL) { + r1->routes[m] = r2->routes[m]; + } + + if (r2->multi_segment_routes[m] != NULL) { + r1->multi_segment_routes[m] = r2->multi_segment_routes[m]; + } + } + + if (r1->single_segment_child != NULL && r2->single_segment_child != NULL) { + __lnm_http_router_merge(r1->single_segment_child, r2->single_segment_child); + } else if (r2->single_segment_child != NULL) { + r1->single_segment_child = r2->single_segment_child; + } + + for (unsigned char c = 0; c < 128; c++) { + if (r1->exact_children[c] != NULL && r2->exact_children[c] != NULL) { + __lnm_http_router_merge(r1->exact_children[c], r2->exact_children[c]); + } else if (r2->exact_children[c] != NULL) { + r1->exact_children[c] = r2->exact_children[c]; + } + } + + r1->represents_route = r1->represents_route || r2->represents_route; + + free(r2); +} + +lnm_err lnm_http_router_merge(lnm_http_router *r1, lnm_http_router *r2) { + if (lnm_http_router_conflicts(r1, r2)) { + return lnm_err_overlapping_route; + } + + __lnm_http_router_merge(r1, r2); + + return lnm_err_ok; +} + +lnm_err lnm_http_router_nest(lnm_http_router *parent, lnm_http_router *child, + const char *prefix) { + size_t prefix_len = strlen(prefix); + + if (!is_ascii(prefix) || prefix[0] != '/' || prefix[prefix_len - 1] == '/') { + return lnm_err_invalid_route; + } + + lnm_http_router *merge_target = parent; + + // The child router's routes are also mounted on '/', so we stop one earlier + // as we need to merge it with the router representing the '/' + while (*(prefix + 1) != '\0') { + unsigned char c = *prefix; + + if (merge_target->exact_children[c] == NULL) { + LNM_RES(lnm_http_router_init(&merge_target->exact_children[c])); + } + + merge_target = merge_target->exact_children[c]; + prefix++; + } + + // We check whether there are any conflicts between the child and the existing + // router + bool conflicting = merge_target->single_segment_child != NULL && + child->single_segment_child != NULL; + + for (lnm_http_method m = 0; !conflicting && m < lnm_http_method_total; m++) { + conflicting = + conflicting || + (merge_target->routes[m] != NULL && child->routes[m] != NULL) || + (merge_target->multi_segment_routes[m] != NULL && + child->multi_segment_routes[m] != NULL); + } + + for (unsigned char c = 0; !conflicting && c < 128; c++) { + conflicting = conflicting || (merge_target->exact_children[c] != NULL && + child->exact_children[c] != NULL); + } + + if (conflicting) { + return lnm_err_overlapping_route; + } + + // Merge routers + merge_target->represents_route = + merge_target->represents_route || child->represents_route; + + if (child->single_segment_child != NULL) { + merge_target->single_segment_child = child->single_segment_child; + } + + for (lnm_http_method m = 0; m < lnm_http_method_total; m++) { + if (child->routes[m] != NULL) { + merge_target->routes[m] = child->routes[m]; + } + + if (child->multi_segment_routes[m] != NULL) { + merge_target->multi_segment_routes[m] = child->multi_segment_routes[m]; + } + } + + for (unsigned char c = 0; c < 128; c++) { + if (child->exact_children[c] != NULL) { + merge_target->exact_children[c] = child->exact_children[c]; + } + } + + free(child); + + return lnm_err_ok; +} diff --git a/test/routing.c b/test/routing.c index e133f4b..b87a243 100644 --- a/test/routing.c +++ b/test/routing.c @@ -1,3 +1,5 @@ +#include "lnm/common.h" +#include "lnm/http/route.h" #include "test.h" #include "lnm/http/loop.h" @@ -51,10 +53,57 @@ void test_routing_star() { TEST_CHECK(lnm_http_router_route(&match, router, lnm_http_method_get, "/hello/world") == lnm_http_route_err_match); TEST_CHECK(match.key_segments[0].start == 1); TEST_CHECK(match.key_segments[0].len == 11); + + lnm_http_router_free(router); +} + +void test_routing_merge() { + lnm_http_router *rtr1, *rtr2; + lnm_http_route *rt1, *rt2; + lnm_http_route_match match; + + TEST_CHECK(lnm_http_router_init(&rtr1) == lnm_err_ok); + TEST_CHECK(lnm_http_router_init(&rtr2) == lnm_err_ok); + + TEST_CHECK(lnm_http_router_add(&rt1, rtr1, lnm_http_method_get, "/*key") == lnm_err_ok); + TEST_CHECK(lnm_http_router_add(NULL, rtr1, lnm_http_method_get, "/:key/hello") == lnm_err_ok); + TEST_CHECK(lnm_http_router_add(&rt2, rtr2, lnm_http_method_get, "/test2") == lnm_err_ok); + TEST_CHECK(lnm_http_router_add(NULL, rtr2, lnm_http_method_get, "/:key/hello2") == lnm_err_ok); + + TEST_CHECK(lnm_http_router_merge(rtr1, rtr2) == lnm_err_ok); + + TEST_CHECK(lnm_http_router_route(&match, rtr1, lnm_http_method_get, "/some/thing") == lnm_http_route_err_match); + TEST_CHECK(match.route == rt1); + + TEST_CHECK(lnm_http_router_route(&match, rtr1, lnm_http_method_get, "/test2") == lnm_http_route_err_match); + TEST_CHECK(match.route == rt2); +} + +void test_routing_nest() { + lnm_http_router *r1; + TEST_CHECK(lnm_http_router_init(&r1) == lnm_err_ok); + + TEST_CHECK(lnm_http_router_add(NULL, r1, lnm_http_method_get, "/*key") == lnm_err_ok); + + lnm_http_router *r2; + TEST_CHECK(lnm_http_router_init(&r2) == lnm_err_ok); + TEST_CHECK(lnm_http_router_add(NULL, r2, lnm_http_method_get, "/test/test2") == lnm_err_ok); + + TEST_CHECK(lnm_http_router_nest(r2, r1, "/test") == lnm_err_ok); + + lnm_http_route_match match; + TEST_CHECK(lnm_http_router_route(&match, r2, lnm_http_method_get, "/test/test_var/secondvar") == lnm_http_route_err_match); + TEST_CHECK(match.key_segments[0].start == 6); + TEST_CHECK(match.key_segments[0].len == 18); + + TEST_CHECK(lnm_http_router_route(&match, r2, lnm_http_method_get, "/test/test2") == lnm_http_route_err_match); + } TEST_LIST = { { "routing simple", test_routing_simple }, { "routing star", test_routing_star }, + { "routing merge", test_routing_merge }, + /* { "routing nest", test_routing_nest }, */ { NULL, NULL } }; From cf4451740f24f6a1a9fcff50fcd8dd7c089a7ca8 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Sat, 2 Mar 2024 11:26:51 +0100 Subject: [PATCH 15/21] feat(routing): implement router nesting --- src/http/lnm_http_router.c | 64 +++++--------------------------------- test/routing.c | 11 +++---- 2 files changed, 12 insertions(+), 63 deletions(-) diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index 552369c..fec6c2e 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -359,74 +359,24 @@ lnm_err lnm_http_router_merge(lnm_http_router *r1, lnm_http_router *r2) { lnm_err lnm_http_router_nest(lnm_http_router *parent, lnm_http_router *child, const char *prefix) { - size_t prefix_len = strlen(prefix); - - if (!is_ascii(prefix) || prefix[0] != '/' || prefix[prefix_len - 1] == '/') { + if (!is_ascii(prefix) || prefix[0] != '/') { return lnm_err_invalid_route; } - lnm_http_router *merge_target = parent; + lnm_http_router *router = parent; // The child router's routes are also mounted on '/', so we stop one earlier // as we need to merge it with the router representing the '/' - while (*(prefix + 1) != '\0') { + while (*prefix != '\0') { unsigned char c = *prefix; - if (merge_target->exact_children[c] == NULL) { - LNM_RES(lnm_http_router_init(&merge_target->exact_children[c])); + if (router->exact_children[c] == NULL) { + LNM_RES(lnm_http_router_init(&router->exact_children[c])); } - merge_target = merge_target->exact_children[c]; + router = router->exact_children[c]; prefix++; } - // We check whether there are any conflicts between the child and the existing - // router - bool conflicting = merge_target->single_segment_child != NULL && - child->single_segment_child != NULL; - - for (lnm_http_method m = 0; !conflicting && m < lnm_http_method_total; m++) { - conflicting = - conflicting || - (merge_target->routes[m] != NULL && child->routes[m] != NULL) || - (merge_target->multi_segment_routes[m] != NULL && - child->multi_segment_routes[m] != NULL); - } - - for (unsigned char c = 0; !conflicting && c < 128; c++) { - conflicting = conflicting || (merge_target->exact_children[c] != NULL && - child->exact_children[c] != NULL); - } - - if (conflicting) { - return lnm_err_overlapping_route; - } - - // Merge routers - merge_target->represents_route = - merge_target->represents_route || child->represents_route; - - if (child->single_segment_child != NULL) { - merge_target->single_segment_child = child->single_segment_child; - } - - for (lnm_http_method m = 0; m < lnm_http_method_total; m++) { - if (child->routes[m] != NULL) { - merge_target->routes[m] = child->routes[m]; - } - - if (child->multi_segment_routes[m] != NULL) { - merge_target->multi_segment_routes[m] = child->multi_segment_routes[m]; - } - } - - for (unsigned char c = 0; c < 128; c++) { - if (child->exact_children[c] != NULL) { - merge_target->exact_children[c] = child->exact_children[c]; - } - } - - free(child); - - return lnm_err_ok; + return lnm_http_router_merge(router, child); } diff --git a/test/routing.c b/test/routing.c index b87a243..805a856 100644 --- a/test/routing.c +++ b/test/routing.c @@ -80,18 +80,17 @@ void test_routing_merge() { } void test_routing_nest() { - lnm_http_router *r1; + lnm_http_router *r1, *r2; + lnm_http_route_match match; + TEST_CHECK(lnm_http_router_init(&r1) == lnm_err_ok); + TEST_CHECK(lnm_http_router_init(&r2) == lnm_err_ok); TEST_CHECK(lnm_http_router_add(NULL, r1, lnm_http_method_get, "/*key") == lnm_err_ok); - - lnm_http_router *r2; - TEST_CHECK(lnm_http_router_init(&r2) == lnm_err_ok); TEST_CHECK(lnm_http_router_add(NULL, r2, lnm_http_method_get, "/test/test2") == lnm_err_ok); TEST_CHECK(lnm_http_router_nest(r2, r1, "/test") == lnm_err_ok); - lnm_http_route_match match; TEST_CHECK(lnm_http_router_route(&match, r2, lnm_http_method_get, "/test/test_var/secondvar") == lnm_http_route_err_match); TEST_CHECK(match.key_segments[0].start == 6); TEST_CHECK(match.key_segments[0].len == 18); @@ -104,6 +103,6 @@ TEST_LIST = { { "routing simple", test_routing_simple }, { "routing star", test_routing_star }, { "routing merge", test_routing_merge }, - /* { "routing nest", test_routing_nest }, */ + { "routing nest", test_routing_nest }, { NULL, NULL } }; From 115baecde8199730f5976299fd26d82d829eb5cc Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Sat, 2 Mar 2024 22:36:58 +0100 Subject: [PATCH 16/21] refactor(routing): moved some stuff, added some comments --- include/lnm/common.h | 8 ++++++ include/lnm/http/route.h | 16 ++++++++++++ src/http/lnm_http_route.c | 25 +++++++++++++++++++ src/http/lnm_http_router.c | 51 ++++++-------------------------------- src/lnm_utils.c | 12 +++++++++ test/routing.c | 3 +++ 6 files changed, 72 insertions(+), 43 deletions(-) diff --git a/include/lnm/common.h b/include/lnm/common.h index eba90a8..a21a439 100644 --- a/include/lnm/common.h +++ b/include/lnm/common.h @@ -89,4 +89,12 @@ uint64_t lnm_atoi(const char *s, size_t len); */ uint64_t lnm_digits(uint64_t num); +/** + * Check whether the given nul-terminated string solely consists of ASCII + * characters. + * + * @param s nul-terminated string to check + */ +bool lnm_is_ascii(const char *s); + #endif diff --git a/include/lnm/http/route.h b/include/lnm/http/route.h index 2d87a1b..4e2d40f 100644 --- a/include/lnm/http/route.h +++ b/include/lnm/http/route.h @@ -45,6 +45,10 @@ lnm_err lnm_http_router_init(lnm_http_router **out); void lnm_http_router_free(lnm_http_router *router); +/** + * Insert a new path & method in the given router, returning a handle to the + * newly created route struct. + */ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, lnm_http_method method, const char *path); @@ -67,14 +71,26 @@ lnm_err lnm_http_router_merge(lnm_http_router *r1, lnm_http_router *r2); lnm_err lnm_http_router_nest(lnm_http_router *parent, lnm_http_router *child, const char *prefix); +/** + * Route the given path & method. + */ lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, const lnm_http_router *router, lnm_http_method method, const char *path); +/** + * Retrieve a path segment using its name. + * + * @return NULL if not found, otherwise pointer to the match segment struct + * representing the key + */ const lnm_http_route_match_segment * lnm_http_route_match_get(lnm_http_route_match *match, const char *key); +/** + * Append the given step function to the route's step list. + */ lnm_err lnm_http_route_step_append(lnm_http_route *route, lnm_http_step_fn fn, bool blocking); diff --git a/src/http/lnm_http_route.c b/src/http/lnm_http_route.c index 9901b79..45de13e 100644 --- a/src/http/lnm_http_route.c +++ b/src/http/lnm_http_route.c @@ -75,6 +75,31 @@ lnm_err lnm_http_route_key_segment_insert(lnm_http_route *route, return lnm_err_ok; } +const lnm_http_route_match_segment * +lnm_http_route_match_get(lnm_http_route_match *match, const char *key) { + if (match->route->key_segments == NULL) { + return NULL; + } + + lnm_http_route_segment_trie *trie = match->route->key_segments; + + while (*key != '\0') { + trie = trie->children[(unsigned char)*key]; + + if (trie == NULL) { + return NULL; + } + + key++; + } + + if (!trie->represents_segment) { + return NULL; + } + + return &match->key_segments[trie->index]; +} + lnm_err lnm_http_step_init(lnm_http_step **out) { lnm_http_step *step = calloc(1, sizeof(lnm_http_step)); diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index fec6c2e..88c7f65 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -34,21 +34,9 @@ void lnm_http_router_free(lnm_http_router *router) { free(router); } -static bool is_ascii(const char *s) { - while (*s != '\0') { - if (*s < 0) { - return false; - } - - s++; - } - - return true; -} - lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, lnm_http_method method, const char *path) { - if (path[0] != '/' || !is_ascii(path)) { + if (path[0] != '/' || !lnm_is_ascii(path)) { return lnm_err_invalid_route; } @@ -63,7 +51,10 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, switch (c) { case ':': { + // Match the segment content as the variable name const char *next_slash_ptr = strchr(path + 1, '/'); + + // Account for segment being the final part of the route const char *new_path = next_slash_ptr == NULL ? strchr(path + 1, '\0') : next_slash_ptr; size_t key_len = new_path - (path + 1); @@ -128,7 +119,6 @@ lnm_err lnm_http_router_add(lnm_http_route **out, lnm_http_router *http_router, http_router->multi_segment_routes[method] = route; goto end; - } break; default: if (http_router->exact_children[c] == NULL) { @@ -218,6 +208,8 @@ static lnm_http_route_err __lnm_http_router_route(lnm_http_route_match *out, matched_key_segments + 1); if (sub_res == lnm_http_route_err_match) { + // If match succeeds down the recursion, we can correctly set the + // matched segments when going back up the stack if (out != NULL) { out->key_segments[matched_key_segments].start = path_index; out->key_segments[matched_key_segments].len = segment_len; @@ -257,38 +249,13 @@ lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, const lnm_http_router *router, lnm_http_method method, const char *path) { - if (!is_ascii(path)) { + if (!lnm_is_ascii(path)) { return lnm_http_route_err_unknown_route; } return __lnm_http_router_route(out, router, method, path, 0, 0); } -const lnm_http_route_match_segment * -lnm_http_route_match_get(lnm_http_route_match *match, const char *key) { - if (match->route->key_segments == NULL) { - return NULL; - } - - lnm_http_route_segment_trie *trie = match->route->key_segments; - - while (*key != '\0') { - trie = trie->children[(unsigned char)*key]; - - if (trie == NULL) { - return NULL; - } - - key++; - } - - if (!trie->represents_segment) { - return NULL; - } - - return &match->key_segments[trie->index]; -} - bool lnm_http_router_conflicts(const lnm_http_router *r1, const lnm_http_router *r2) { // First check the literal routes for the routers @@ -359,14 +326,12 @@ lnm_err lnm_http_router_merge(lnm_http_router *r1, lnm_http_router *r2) { lnm_err lnm_http_router_nest(lnm_http_router *parent, lnm_http_router *child, const char *prefix) { - if (!is_ascii(prefix) || prefix[0] != '/') { + if (!lnm_is_ascii(prefix) || prefix[0] != '/') { return lnm_err_invalid_route; } lnm_http_router *router = parent; - // The child router's routes are also mounted on '/', so we stop one earlier - // as we need to merge it with the router representing the '/' while (*prefix != '\0') { unsigned char c = *prefix; diff --git a/src/lnm_utils.c b/src/lnm_utils.c index 85094bd..849c31f 100644 --- a/src/lnm_utils.c +++ b/src/lnm_utils.c @@ -55,3 +55,15 @@ uint64_t lnm_digits(uint64_t num) { return digits; } + +bool lnm_is_ascii(const char *s) { + bool valid = true; + + while (valid && *s != '\0') { + valid = *s < 0; + + s++; + } + + return valid; +} diff --git a/test/routing.c b/test/routing.c index 805a856..827d4c5 100644 --- a/test/routing.c +++ b/test/routing.c @@ -77,6 +77,8 @@ void test_routing_merge() { TEST_CHECK(lnm_http_router_route(&match, rtr1, lnm_http_method_get, "/test2") == lnm_http_route_err_match); TEST_CHECK(match.route == rt2); + + lnm_http_router_free(rtr1); } void test_routing_nest() { @@ -97,6 +99,7 @@ void test_routing_nest() { TEST_CHECK(lnm_http_router_route(&match, r2, lnm_http_method_get, "/test/test2") == lnm_http_route_err_match); + lnm_http_router_free(r2); } TEST_LIST = { From 6eab5d616c2772a625b521e19d50020156c72ca2 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Sat, 2 Mar 2024 22:51:40 +0100 Subject: [PATCH 17/21] fix: flip is_ascii check --- src/lnm_utils.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lnm_utils.c b/src/lnm_utils.c index 849c31f..47989bf 100644 --- a/src/lnm_utils.c +++ b/src/lnm_utils.c @@ -59,8 +59,8 @@ uint64_t lnm_digits(uint64_t num) { bool lnm_is_ascii(const char *s) { bool valid = true; - while (valid && *s != '\0') { - valid = *s < 0; + while (valid && (*s != '\0')) { + valid = *s >= 0; s++; } From 195eb9eb4832f80ee8ab2372192196018362b252 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Sat, 9 Mar 2024 20:28:50 +0100 Subject: [PATCH 18/21] chore: remove unneeded code; add throughput example --- Makefile | 2 +- example/throughput.c | 53 ++++++++++++++++++++++++++++++++++++++++++ include/lnm/http/req.h | 1 - 3 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 example/throughput.c diff --git a/Makefile b/Makefile index e52bb1f..be76159 100644 --- a/Makefile +++ b/Makefile @@ -81,7 +81,7 @@ $(BUILD_DIR)/$(TEST_DIR)/%.c.o: $(TEST_DIR)/%.c build-example: $(BINS_EXAMPLE) $(BINS_EXAMPLE): %: %.c.o $(LIB) - $(CC) \ + $(CC) $(LDFLAGS) \ $^ -o $@ # Example binaries link the resulting library diff --git a/example/throughput.c b/example/throughput.c new file mode 100644 index 0000000..b2704a8 --- /dev/null +++ b/example/throughput.c @@ -0,0 +1,53 @@ +#include "lnm/http/res.h" +#include "lnm/log.h" +#include "lnm/http/loop.h" +#include "lnm/loop.h" + +lnm_err ctx_init(void **c_ctx, void *gctx) { + *c_ctx = NULL; + + return lnm_err_ok; +} + +void ctx_reset(void *c_ctx) {} +void ctx_free(void *c_ctx) {} + +lnm_err data_streamer(uint64_t *written, char *buf, + lnm_http_conn *conn, uint64_t offset, + uint64_t len) { + // Don't do anything, just let the application return random data stored in + // the read buffer. The goal is to benchmark the networking pipeline + *written = len; + + return lnm_err_ok; +} + +lnm_http_step_err step_fn(lnm_http_conn *conn) { + lnm_http_loop_ctx *ctx = conn->ctx; + uint64_t len = 1 << 30; + lnm_http_res_body_set_fn(&ctx->res, data_streamer, len); + + return lnm_http_step_err_done; +} + +int main() { + lnm_http_loop *hl; + + lnm_http_loop_init(&hl, NULL, ctx_init, + ctx_reset, + ctx_free); + + lnm_http_router *router; + lnm_http_router_init(&router); + + lnm_http_route *route; + lnm_http_router_add(&route, router, lnm_http_method_get, "/"); + lnm_http_route_step_append(route, step_fn, false); + + lnm_http_loop_router_set(hl, router); + + lnm_log_init_global(); + lnm_log_register_stdout(lnm_log_level_warning); + + printf("res = %i\n", lnm_http_loop_run(hl, 8080, 1, 0)); +} diff --git a/include/lnm/http/req.h b/include/lnm/http/req.h index 1c32972..146fb81 100644 --- a/include/lnm/http/req.h +++ b/include/lnm/http/req.h @@ -40,7 +40,6 @@ typedef struct lnm_http_req { struct { size_t o; size_t len; - regmatch_t groups[LNM_HTTP_MAX_REGEX_GROUPS]; } path; struct { size_t o; From 5ff788c108a2428ba612fe992eacc6ed7c660751 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Sat, 30 Mar 2024 10:52:43 +0100 Subject: [PATCH 19/21] refactor(test): compile tests into single binary --- Makefile | 23 +- test/{test.h => acutest.h} | 939 +++++++++++++++++++++---------------- test/{ => lnm}/routing.c | 15 +- test/runner.c | 10 + test/tests.h | 9 + 5 files changed, 578 insertions(+), 418 deletions(-) rename test/{test.h => acutest.h} (71%) rename test/{ => lnm}/routing.c (94%) create mode 100644 test/runner.c create mode 100644 test/tests.h diff --git a/Makefile b/Makefile index be76159..9041b06 100644 --- a/Makefile +++ b/Makefile @@ -17,7 +17,7 @@ OBJS_EXAMPLE := $(SRCS_EXAMPLE:%=$(BUILD_DIR)/%.o) DEPS := $(SRCS:%=$(BUILD_DIR)/%.d) $(SRCS_TEST:%=$(BUILD_DIR)/%.d) -BINS_TEST := $(OBJS_TEST:%.c.o=%) +BIN_TEST := $(BUILD_DIR)/$(TEST_DIR)/runner BINS_EXAMPLE := $(OBJS_EXAMPLE:%.c.o=%) TARGETS_TEST := $(BINS_TEST:%=test-%) @@ -46,25 +46,18 @@ $(BUILD_DIR)/$(SRC_DIR)/%.c.o: $(SRC_DIR)/%.c # =====TESTING===== .PHONY: test -test: $(TARGETS_TEST) +test: $(BIN_TEST) + './$^' .PHONY: test-mem -test-mem: $(TARGETS_MEM_TEST) - -.PHONY: $(TARGETS_TEST) -$(TARGETS_TEST): test-%: % - ./$^ - -.PHONY: $(TARGETS_MEM_TEST) -$(TARGETS_MEM_TEST): test-mem-%: % - valgrind --tool=memcheck --error-exitcode=1 --track-origins=yes --leak-check=full ./$^ +test-mem: $(BIN_TEST) + valgrind --tool=memcheck --error-exitcode=1 --track-origins=yes --leak-check=full './$^' .PHONY: build-test -build-test: $(BINS_TEST) +build-test: $(BIN_TEST) -$(BINS_TEST): %: %.c.o $(LIB) - $(CC) \ - $^ -o $@ +$(BIN_TEST): $(OBJS_TEST) $(LIB) + $(CC) -o $@ $^ $(_LDFLAGS) # Along with the include directory, each test includes $(TEST_DIR) (which # contains the acutest.h header file), and the src directory of the module it's diff --git a/test/test.h b/test/acutest.h similarity index 71% rename from test/test.h rename to test/acutest.h index 9ab8f88..5f9cb19 100644 --- a/test/test.h +++ b/test/acutest.h @@ -2,7 +2,7 @@ * Acutest -- Another C/C++ Unit Test facility * * - * Copyright 2013-2020 Martin Mitas + * Copyright 2013-2023 Martin Mitáš * Copyright 2019 Garrett D'Amore * * Permission is hereby granted, free of charge, to any person obtaining a @@ -28,6 +28,19 @@ #define ACUTEST_H +/* Try to auto-detect whether we need to disable C++ exception handling. + * If the detection fails, you may always define TEST_NO_EXCEPTIONS before + * including "acutest.h" manually. */ +#ifdef __cplusplus + #if (__cplusplus >= 199711L && !defined __cpp_exceptions) || \ + ((defined(__GNUC__) || defined(__clang__)) && !defined __EXCEPTIONS) + #ifndef TEST_NO_EXCEPTIONS + #define TEST_NO_EXCEPTIONS + #endif + #endif +#endif + + /************************ *** Public interface *** ************************/ @@ -81,8 +94,10 @@ * TEST_CHECK(ptr->member2 > 200); * } */ -#define TEST_CHECK_(cond,...) acutest_check_((cond), __FILE__, __LINE__, __VA_ARGS__) -#define TEST_CHECK(cond) acutest_check_((cond), __FILE__, __LINE__, "%s", #cond) +#define TEST_CHECK_(cond,...) \ + acutest_check_(!!(cond), __FILE__, __LINE__, __VA_ARGS__) +#define TEST_CHECK(cond) \ + acutest_check_(!!(cond), __FILE__, __LINE__, "%s", #cond) /* These macros are the same as TEST_CHECK_ and TEST_CHECK except that if the @@ -102,17 +117,18 @@ */ #define TEST_ASSERT_(cond,...) \ do { \ - if(!acutest_check_((cond), __FILE__, __LINE__, __VA_ARGS__)) \ + if(!acutest_check_(!!(cond), __FILE__, __LINE__, __VA_ARGS__)) \ acutest_abort_(); \ } while(0) #define TEST_ASSERT(cond) \ do { \ - if(!acutest_check_((cond), __FILE__, __LINE__, "%s", #cond)) \ + if(!acutest_check_(!!(cond), __FILE__, __LINE__, "%s", #cond)) \ acutest_abort_(); \ } while(0) #ifdef __cplusplus +#ifndef TEST_NO_EXCEPTIONS /* Macros to verify that the code (the 1st argument) throws exception of given * type (the 2nd argument). (Note these macros are only available in C++.) * @@ -159,6 +175,7 @@ if(msg_ != NULL) \ acutest_message_("%s", msg_); \ } while(0) +#endif /* #ifndef TEST_NO_EXCEPTIONS */ #endif /* #ifdef __cplusplus */ @@ -188,7 +205,7 @@ * You may define another limit prior including "acutest.h" */ #ifndef TEST_CASE_MAXSIZE -#define TEST_CASE_MAXSIZE 64 + #define TEST_CASE_MAXSIZE 64 #endif @@ -220,7 +237,7 @@ * You may define another limit prior including "acutest.h" */ #ifndef TEST_MSG_MAXSIZE -#define TEST_MSG_MAXSIZE 1024 + #define TEST_MSG_MAXSIZE 1024 #endif @@ -241,11 +258,21 @@ * You may define another limit prior including "acutest.h" */ #ifndef TEST_DUMP_MAXSIZE -#define TEST_DUMP_MAXSIZE 1024 + #define TEST_DUMP_MAXSIZE 1024 #endif -/* Common test initialiation/clean-up +/* Macros for marking the test as SKIPPED. + * Note it can only be used at the beginning of a test, before any other + * checking. + * + * Once used, the best practice is to return from the test routine as soon + * as possible. + */ +#define TEST_SKIP(...) acutest_skip_(__FILE__, __LINE__, __VA_ARGS__) + + +/* Common test initialisation/clean-up * * In some test suites, it may be needed to perform some sort of the same * initialization and/or clean-up in all the tests. @@ -272,42 +299,77 @@ /* The unit test files should not rely on anything below. */ +#include + +/* Enable the use of the non-standard keyword __attribute__ to silence warnings under some compilers */ +#if defined(__GNUC__) || defined(__clang__) + #define ACUTEST_ATTRIBUTE_(attr) __attribute__((attr)) +#else + #define ACUTEST_ATTRIBUTE_(attr) +#endif + +#ifdef __cplusplus + extern "C" { +#endif + +enum acutest_state_ { + ACUTEST_STATE_INITIAL = -4, + ACUTEST_STATE_SELECTED = -3, + ACUTEST_STATE_NEEDTORUN = -2, + + /* By the end all tests should be in one of the following: */ + ACUTEST_STATE_EXCLUDED = -1, + ACUTEST_STATE_SUCCESS = 0, + ACUTEST_STATE_FAILED = 1, + ACUTEST_STATE_SKIPPED = 2 +}; + +int acutest_check_(int cond, const char* file, int line, const char* fmt, ...); +void acutest_case_(const char* fmt, ...); +void acutest_message_(const char* fmt, ...); +void acutest_dump_(const char* title, const void* addr, size_t size); +void acutest_abort_(void) ACUTEST_ATTRIBUTE_(noreturn); +#ifdef __cplusplus + } /* extern "C" */ +#endif + +#ifndef TEST_NO_MAIN + #include #include #include -#include #include #include #if defined(unix) || defined(__unix__) || defined(__unix) || defined(__APPLE__) -#define ACUTEST_UNIX_ 1 -#include -#include -#include -#include -#include -#include -#include + #define ACUTEST_UNIX_ 1 + #include + #include + #include + #include + #include + #include + #include -#if defined CLOCK_PROCESS_CPUTIME_ID && defined CLOCK_MONOTONIC -#define ACUTEST_HAS_POSIX_TIMER_ 1 -#endif + #if defined CLOCK_PROCESS_CPUTIME_ID && defined CLOCK_MONOTONIC + #define ACUTEST_HAS_POSIX_TIMER_ 1 + #endif #endif #if defined(_gnu_linux_) || defined(__linux__) -#define ACUTEST_LINUX_ 1 -#include -#include + #define ACUTEST_LINUX_ 1 + #include + #include #endif #if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__) -#define ACUTEST_WIN_ 1 + #define ACUTEST_WIN_ 1 #include #include #endif #if defined(__APPLE__) -#define ACUTEST_MACOS_ + #define ACUTEST_MACOS_ #include #include #include @@ -316,31 +378,26 @@ #endif #ifdef __cplusplus -#include +#ifndef TEST_NO_EXCEPTIONS + #include +#endif #endif #ifdef __has_include -#if __has_include() -#include -#endif -#endif - -/* Enable the use of the non-standard keyword __attribute__ to silence warnings under some compilers */ -#if defined(__GNUC__) || defined(__clang__) -#define ACUTEST_ATTRIBUTE_(attr) __attribute__((attr)) -#else -#define ACUTEST_ATTRIBUTE_(attr) + #if __has_include() + #include + #endif #endif /* Note our global private identifiers end with '_' to mitigate risk of clash * with the unit tests implementation. */ #ifdef __cplusplus -extern "C" { + extern "C" { #endif #ifdef _MSC_VER -/* In the multi-platform code like ours, we cannot use the non-standard + /* In the multi-platform code like ours, we cannot use the non-standard * "safe" functions from Microsoft C lib like e.g. sprintf_s() instead of * standard sprintf(). Hence, lets disable the warning C4996. */ #pragma warning(push) @@ -354,47 +411,32 @@ struct acutest_test_ { }; struct acutest_test_data_ { - unsigned char flags; + enum acutest_state_ state; double duration; }; -enum { - ACUTEST_FLAG_RUN_ = 1 << 0, - ACUTEST_FLAG_SUCCESS_ = 1 << 1, - ACUTEST_FLAG_FAILURE_ = 1 << 2, -}; extern const struct acutest_test_ acutest_list_[]; -int acutest_check_(int cond, const char* file, int line, const char* fmt, ...); -void acutest_case_(const char* fmt, ...); -void acutest_message_(const char* fmt, ...); -void acutest_dump_(const char* title, const void* addr, size_t size); -void acutest_abort_(void) ACUTEST_ATTRIBUTE_(noreturn); - - -#ifndef TEST_NO_MAIN static char* acutest_argv0_ = NULL; -static size_t acutest_list_size_ = 0; +static int acutest_list_size_ = 0; static struct acutest_test_data_* acutest_test_data_ = NULL; -static size_t acutest_count_ = 0; static int acutest_no_exec_ = -1; static int acutest_no_summary_ = 0; static int acutest_tap_ = 0; -static int acutest_skip_mode_ = 0; +static int acutest_exclude_mode_ = 0; static int acutest_worker_ = 0; static int acutest_worker_index_ = 0; static int acutest_cond_failed_ = 0; -static int acutest_was_aborted_ = 0; static FILE *acutest_xml_output_ = NULL; -static int acutest_stat_failed_units_ = 0; -static int acutest_stat_run_units_ = 0; - static const struct acutest_test_* acutest_current_test_ = NULL; static int acutest_current_index_ = 0; static char acutest_case_name_[TEST_CASE_MAXSIZE] = ""; +static int acutest_test_check_count_ = 0; +static int acutest_test_skip_count_ = 0; +static char acutest_test_skip_reason_[256] = ""; static int acutest_test_already_logged_ = 0; static int acutest_case_already_logged_ = 0; static int acutest_verbose_level_ = 2; @@ -405,6 +447,18 @@ static int acutest_timer_ = 0; static int acutest_abort_has_jmp_buf_ = 0; static jmp_buf acutest_abort_jmp_buf_; +static int +acutest_count_(enum acutest_state_ state) +{ + int i, n; + + for(i = 0, n = 0; i < acutest_list_size_; i++) { + if(acutest_test_data_[i].state == state) + n++; + } + + return n; +} static void acutest_cleanup_(void) @@ -419,8 +473,9 @@ acutest_exit_(int exit_code) exit(exit_code); } + #if defined ACUTEST_WIN_ -typedef LARGE_INTEGER acutest_timer_type_; + typedef LARGE_INTEGER acutest_timer_type_; static LARGE_INTEGER acutest_timer_freq_; static acutest_timer_type_ acutest_timer_start_; static acutest_timer_type_ acutest_timer_end_; @@ -451,51 +506,40 @@ typedef LARGE_INTEGER acutest_timer_type_; printf("%.6lf secs", acutest_timer_diff_(acutest_timer_start_, acutest_timer_end_)); } #elif defined ACUTEST_HAS_POSIX_TIMER_ -static clockid_t acutest_timer_id_; -typedef struct timespec acutest_timer_type_; -static acutest_timer_type_ acutest_timer_start_; -static acutest_timer_type_ acutest_timer_end_; + static clockid_t acutest_timer_id_; + typedef struct timespec acutest_timer_type_; + static acutest_timer_type_ acutest_timer_start_; + static acutest_timer_type_ acutest_timer_end_; -static void -acutest_timer_init_(void) -{ - if(acutest_timer_ == 1) - acutest_timer_id_ = CLOCK_MONOTONIC; - else if(acutest_timer_ == 2) - acutest_timer_id_ = CLOCK_PROCESS_CPUTIME_ID; -} + static void + acutest_timer_init_(void) + { + if(acutest_timer_ == 1) + acutest_timer_id_ = CLOCK_MONOTONIC; + else if(acutest_timer_ == 2) + acutest_timer_id_ = CLOCK_PROCESS_CPUTIME_ID; + } -static void -acutest_timer_get_time_(struct timespec* ts) -{ - clock_gettime(acutest_timer_id_, ts); -} + static void + acutest_timer_get_time_(struct timespec* ts) + { + clock_gettime(acutest_timer_id_, ts); + } -static double -acutest_timer_diff_(struct timespec start, struct timespec end) -{ - double endns; - double startns; + static double + acutest_timer_diff_(struct timespec start, struct timespec end) + { + return (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1e9; + } - endns = end.tv_sec; - endns *= 1e9; - endns += end.tv_nsec; - - startns = start.tv_sec; - startns *= 1e9; - startns += start.tv_nsec; - - return ((endns - startns)/ 1e9); -} - -static void -acutest_timer_print_diff_(void) -{ - printf("%.6lf secs", - acutest_timer_diff_(acutest_timer_start_, acutest_timer_end_)); -} + static void + acutest_timer_print_diff_(void) + { + printf("%.6lf secs", + acutest_timer_diff_(acutest_timer_start_, acutest_timer_end_)); + } #else -typedef int acutest_timer_type_; + typedef int acutest_timer_type_; static acutest_timer_type_ acutest_timer_start_; static acutest_timer_type_ acutest_timer_end_; @@ -523,11 +567,13 @@ typedef int acutest_timer_type_; #endif #define ACUTEST_COLOR_DEFAULT_ 0 -#define ACUTEST_COLOR_GREEN_ 1 -#define ACUTEST_COLOR_RED_ 2 -#define ACUTEST_COLOR_DEFAULT_INTENSIVE_ 3 -#define ACUTEST_COLOR_GREEN_INTENSIVE_ 4 -#define ACUTEST_COLOR_RED_INTENSIVE_ 5 +#define ACUTEST_COLOR_RED_ 1 +#define ACUTEST_COLOR_GREEN_ 2 +#define ACUTEST_COLOR_YELLOW_ 3 +#define ACUTEST_COLOR_DEFAULT_INTENSIVE_ 10 +#define ACUTEST_COLOR_RED_INTENSIVE_ 11 +#define ACUTEST_COLOR_GREEN_INTENSIVE_ 12 +#define ACUTEST_COLOR_YELLOW_INTENSIVE_ 13 static int ACUTEST_ATTRIBUTE_(format (printf, 2, 3)) acutest_colored_printf_(int color, const char* fmt, ...) @@ -549,10 +595,12 @@ acutest_colored_printf_(int color, const char* fmt, ...) { const char* col_str; switch(color) { - case ACUTEST_COLOR_GREEN_: col_str = "\033[0;32m"; break; case ACUTEST_COLOR_RED_: col_str = "\033[0;31m"; break; - case ACUTEST_COLOR_GREEN_INTENSIVE_: col_str = "\033[1;32m"; break; + case ACUTEST_COLOR_GREEN_: col_str = "\033[0;32m"; break; + case ACUTEST_COLOR_YELLOW_: col_str = "\033[0;33m"; break; case ACUTEST_COLOR_RED_INTENSIVE_: col_str = "\033[1;31m"; break; + case ACUTEST_COLOR_GREEN_INTENSIVE_: col_str = "\033[1;32m"; break; + case ACUTEST_COLOR_YELLOW_INTENSIVE_: col_str = "\033[1;33m"; break; case ACUTEST_COLOR_DEFAULT_INTENSIVE_: col_str = "\033[1m"; break; default: col_str = "\033[0m"; break; } @@ -571,11 +619,13 @@ acutest_colored_printf_(int color, const char* fmt, ...) GetConsoleScreenBufferInfo(h, &info); switch(color) { - case ACUTEST_COLOR_GREEN_: attr = FOREGROUND_GREEN; break; case ACUTEST_COLOR_RED_: attr = FOREGROUND_RED; break; - case ACUTEST_COLOR_GREEN_INTENSIVE_: attr = FOREGROUND_GREEN | FOREGROUND_INTENSITY; break; + case ACUTEST_COLOR_GREEN_: attr = FOREGROUND_GREEN; break; + case ACUTEST_COLOR_YELLOW_: attr = FOREGROUND_RED | FOREGROUND_GREEN; break; case ACUTEST_COLOR_RED_INTENSIVE_: attr = FOREGROUND_RED | FOREGROUND_INTENSITY; break; + case ACUTEST_COLOR_GREEN_INTENSIVE_: attr = FOREGROUND_GREEN | FOREGROUND_INTENSITY; break; case ACUTEST_COLOR_DEFAULT_INTENSIVE_: attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY; break; + case ACUTEST_COLOR_YELLOW_INTENSIVE_: attr = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; break; default: attr = 0; break; } if(attr != 0) @@ -590,6 +640,35 @@ acutest_colored_printf_(int color, const char* fmt, ...) #endif } +static const char* +acutest_basename_(const char* path) +{ + const char* name; + + name = strrchr(path, '/'); + if(name != NULL) + name++; + else + name = path; + +#ifdef ACUTEST_WIN_ + { + const char* alt_name; + + alt_name = strrchr(path, '\\'); + if(alt_name != NULL) + alt_name++; + else + alt_name = path; + + if(alt_name > name) + name = alt_name; + } +#endif + + return name; +} + static void acutest_begin_test_line_(const struct acutest_test_* test) { @@ -612,26 +691,36 @@ acutest_begin_test_line_(const struct acutest_test_* test) } static void -acutest_finish_test_line_(int result) +acutest_finish_test_line_(enum acutest_state_ state) { if(acutest_tap_) { - const char* str = (result == 0) ? "ok" : "not ok"; + printf("%s %d - %s%s\n", + (state == ACUTEST_STATE_SUCCESS || state == ACUTEST_STATE_SKIPPED) ? "ok" : "not ok", + acutest_current_index_ + 1, + acutest_current_test_->name, + (state == ACUTEST_STATE_SKIPPED) ? " # SKIP" : ""); - printf("%s %d - %s\n", str, acutest_current_index_ + 1, acutest_current_test_->name); - - if(result == 0 && acutest_timer_) { + if(state == ACUTEST_STATE_SUCCESS && acutest_timer_) { printf("# Duration: "); acutest_timer_print_diff_(); printf("\n"); } } else { - int color = (result == 0) ? ACUTEST_COLOR_GREEN_INTENSIVE_ : ACUTEST_COLOR_RED_INTENSIVE_; - const char* str = (result == 0) ? "OK" : "FAILED"; + int color; + const char* str; + + switch(state) { + case ACUTEST_STATE_SUCCESS: color = ACUTEST_COLOR_GREEN_INTENSIVE_; str = "OK"; break; + case ACUTEST_STATE_SKIPPED: color = ACUTEST_COLOR_YELLOW_INTENSIVE_; str = "SKIPPED"; break; + case ACUTEST_STATE_FAILED: /* Fall through. */ + default: color = ACUTEST_COLOR_RED_INTENSIVE_; str = "FAILED"; break; + } + printf("[ "); acutest_colored_printf_(color, "%s", str); printf(" ]"); - if(result == 0 && acutest_timer_) { + if(state == ACUTEST_STATE_SUCCESS && acutest_timer_) { printf(" "); acutest_timer_print_diff_(); } @@ -658,6 +747,51 @@ acutest_line_indent_(int level) printf("%.*s", n, spaces); } +void ACUTEST_ATTRIBUTE_(format (printf, 3, 4)) +acutest_skip_(const char* file, int line, const char* fmt, ...) +{ + va_list args; + size_t reason_len; + + va_start(args, fmt); + vsnprintf(acutest_test_skip_reason_, sizeof(acutest_test_skip_reason_), fmt, args); + va_end(args); + acutest_test_skip_reason_[sizeof(acutest_test_skip_reason_)-1] = '\0'; + + /* Remove final dot, if provided; that collides with our other logic. */ + reason_len = strlen(acutest_test_skip_reason_); + if(acutest_test_skip_reason_[reason_len-1] == '.') + acutest_test_skip_reason_[reason_len-1] = '\0'; + + if(acutest_test_check_count_ > 0) { + acutest_check_(0, file, line, "Cannot skip, already performed some checks"); + return; + } + + if(acutest_verbose_level_ >= 2) { + const char *result_str = "skipped"; + int result_color = ACUTEST_COLOR_YELLOW_; + + if(!acutest_test_already_logged_ && acutest_current_test_ != NULL) + acutest_finish_test_line_(ACUTEST_STATE_SKIPPED); + acutest_test_already_logged_++; + + acutest_line_indent_(1); + + if(file != NULL) { + file = acutest_basename_(file); + printf("%s:%d: ", file, line); + } + + printf("%s... ", acutest_test_skip_reason_); + acutest_colored_printf_(result_color, "%s", result_str); + printf("\n"); + acutest_test_already_logged_++; + } + + acutest_test_skip_count_++; +} + int ACUTEST_ATTRIBUTE_(format (printf, 4, 5)) acutest_check_(int cond, const char* file, int line, const char* fmt, ...) { @@ -665,19 +799,28 @@ acutest_check_(int cond, const char* file, int line, const char* fmt, ...) int result_color; int verbose_level; + if(acutest_test_skip_count_) { + /* We've skipped the test. We shouldn't be here: The test implementation + * should have already return before. So lets suppress the following + * output. */ + cond = 1; + goto skip_check; + } + if(cond) { result_str = "ok"; result_color = ACUTEST_COLOR_GREEN_; verbose_level = 3; } else { if(!acutest_test_already_logged_ && acutest_current_test_ != NULL) - acutest_finish_test_line_(-1); + acutest_finish_test_line_(ACUTEST_STATE_FAILED); + + acutest_test_failures_++; + acutest_test_already_logged_++; result_str = "failed"; result_color = ACUTEST_COLOR_RED_; verbose_level = 2; - acutest_test_failures_++; - acutest_test_already_logged_++; } if(acutest_verbose_level_ >= verbose_level) { @@ -692,20 +835,8 @@ acutest_check_(int cond, const char* file, int line, const char* fmt, ...) acutest_line_indent_(acutest_case_name_[0] ? 2 : 1); if(file != NULL) { -#ifdef ACUTEST_WIN_ - const char* lastsep1 = strrchr(file, '\\'); - const char* lastsep2 = strrchr(file, '/'); - if(lastsep1 == NULL) - lastsep1 = file-1; - if(lastsep2 == NULL) - lastsep2 = file-1; - file = (lastsep1 > lastsep2 ? lastsep1 : lastsep2) + 1; -#else - const char* lastsep = strrchr(file, '/'); - if(lastsep != NULL) - file = lastsep+1; -#endif - printf("%s:%d: Check ", file, line); + file = acutest_basename_(file); + printf("%s:%d: ", file, line); } va_start(args, fmt); @@ -718,6 +849,9 @@ acutest_check_(int cond, const char* file, int line, const char* fmt, ...) acutest_test_already_logged_++; } + acutest_test_check_count_++; + +skip_check: acutest_cond_failed_ = (cond == 0); return !acutest_cond_failed_; } @@ -875,7 +1009,9 @@ acutest_abort_(void) } else { if(acutest_current_test_ != NULL) acutest_fini_(acutest_current_test_->name); - abort(); + fflush(stdout); + fflush(stderr); + acutest_exit_(ACUTEST_STATE_FAILED); } } @@ -889,28 +1025,6 @@ acutest_list_names_(void) printf(" %s\n", test->name); } -static void -acutest_remember_(int i) -{ - if(acutest_test_data_[i].flags & ACUTEST_FLAG_RUN_) - return; - - acutest_test_data_[i].flags |= ACUTEST_FLAG_RUN_; - acutest_count_++; -} - -static void -acutest_set_success_(int i, int success) -{ - acutest_test_data_[i].flags |= success ? ACUTEST_FLAG_SUCCESS_ : ACUTEST_FLAG_FAILURE_; -} - -static void -acutest_set_duration_(int i, double duration) -{ - acutest_test_data_[i].duration = duration; -} - static int acutest_name_contains_word_(const char* name, const char* pattern) { @@ -935,15 +1049,15 @@ acutest_name_contains_word_(const char* name, const char* pattern) } static int -acutest_lookup_(const char* pattern) +acutest_select_(const char* pattern) { int i; int n = 0; /* Try exact match. */ - for(i = 0; i < (int) acutest_list_size_; i++) { + for(i = 0; i < acutest_list_size_; i++) { if(strcmp(acutest_list_[i].name, pattern) == 0) { - acutest_remember_(i); + acutest_test_data_[i].state = ACUTEST_STATE_SELECTED; n++; break; } @@ -952,9 +1066,9 @@ acutest_lookup_(const char* pattern) return n; /* Try word match. */ - for(i = 0; i < (int) acutest_list_size_; i++) { + for(i = 0; i < acutest_list_size_; i++) { if(acutest_name_contains_word_(acutest_list_[i].name, pattern)) { - acutest_remember_(i); + acutest_test_data_[i].state = ACUTEST_STATE_SELECTED; n++; } } @@ -962,9 +1076,9 @@ acutest_lookup_(const char* pattern) return n; /* Try relaxed match. */ - for(i = 0; i < (int) acutest_list_size_; i++) { + for(i = 0; i < acutest_list_size_; i++) { if(strstr(acutest_list_[i].name, pattern) != NULL) { - acutest_remember_(i); + acutest_test_data_[i].state = ACUTEST_STATE_SELECTED; n++; } } @@ -1000,73 +1114,87 @@ acutest_error_(const char* fmt, ...) } /* Call directly the given test unit function. */ -static int +static enum acutest_state_ acutest_do_run_(const struct acutest_test_* test, int index) { - int status = -1; + enum acutest_state_ state = ACUTEST_STATE_FAILED; - acutest_was_aborted_ = 0; acutest_current_test_ = test; acutest_current_index_ = index; acutest_test_failures_ = 0; acutest_test_already_logged_ = 0; + acutest_test_check_count_ = 0; + acutest_test_skip_count_ = 0; acutest_cond_failed_ = 0; #ifdef __cplusplus +#ifndef TEST_NO_EXCEPTIONS try { #endif - acutest_init_(test->name); - acutest_begin_test_line_(test); +#endif + acutest_init_(test->name); + acutest_begin_test_line_(test); - /* This is good to do in case the test unit crashes. */ - fflush(stdout); - fflush(stderr); + /* This is good to do in case the test unit crashes. */ + fflush(stdout); + fflush(stderr); - if(!acutest_worker_) { - acutest_abort_has_jmp_buf_ = 1; - if(setjmp(acutest_abort_jmp_buf_) != 0) { - acutest_was_aborted_ = 1; - goto aborted; + if(!acutest_worker_) { + acutest_abort_has_jmp_buf_ = 1; + if(setjmp(acutest_abort_jmp_buf_) != 0) + goto aborted; } - } - acutest_timer_get_time_(´st_timer_start_); - test->func(); - aborted: - acutest_abort_has_jmp_buf_ = 0; - acutest_timer_get_time_(´st_timer_end_); + acutest_timer_get_time_(´st_timer_start_); + test->func(); - if(acutest_verbose_level_ >= 3) { - acutest_line_indent_(1); - if(acutest_test_failures_ == 0) { - acutest_colored_printf_(ACUTEST_COLOR_GREEN_INTENSIVE_, "SUCCESS: "); - printf("All conditions have passed.\n"); +aborted: + acutest_abort_has_jmp_buf_ = 0; + acutest_timer_get_time_(´st_timer_end_); - if(acutest_timer_) { - acutest_line_indent_(1); - printf("Duration: "); - acutest_timer_print_diff_(); - printf("\n"); - } - } else { - acutest_colored_printf_(ACUTEST_COLOR_RED_INTENSIVE_, "FAILED: "); - if(!acutest_was_aborted_) { - printf("%d condition%s %s failed.\n", - acutest_test_failures_, - (acutest_test_failures_ == 1) ? "" : "s", - (acutest_test_failures_ == 1) ? "has" : "have"); - } else { - printf("Aborted.\n"); + if(acutest_test_failures_ > 0) + state = ACUTEST_STATE_FAILED; + else if(acutest_test_skip_count_ > 0) + state = ACUTEST_STATE_SKIPPED; + else + state = ACUTEST_STATE_SUCCESS; + + if(!acutest_test_already_logged_) + acutest_finish_test_line_(state); + + if(acutest_verbose_level_ >= 3) { + acutest_line_indent_(1); + switch(state) { + case ACUTEST_STATE_SUCCESS: + acutest_colored_printf_(ACUTEST_COLOR_GREEN_INTENSIVE_, "SUCCESS: "); + printf("All conditions have passed.\n"); + + if(acutest_timer_) { + acutest_line_indent_(1); + printf("Duration: "); + acutest_timer_print_diff_(); + printf("\n"); + } + break; + + case ACUTEST_STATE_SKIPPED: + acutest_colored_printf_(ACUTEST_COLOR_YELLOW_INTENSIVE_, "SKIPPED: "); + printf("%s.\n", acutest_test_skip_reason_); + break; + + default: + acutest_colored_printf_(ACUTEST_COLOR_RED_INTENSIVE_, "FAILED: "); + printf("%d condition%s %s failed.\n", + acutest_test_failures_, + (acutest_test_failures_ == 1) ? "" : "s", + (acutest_test_failures_ == 1) ? "has" : "have"); + break; } + printf("\n"); } - printf("\n"); - } else if(acutest_verbose_level_ >= 1 && acutest_test_failures_ == 0) { - acutest_finish_test_line_(0); - } - - status = (acutest_test_failures_ == 0) ? 0 : -1; #ifdef __cplusplus +#ifndef TEST_NO_EXCEPTIONS } catch(std::exception& e) { const char* what = e.what(); acutest_check_(0, NULL, 0, "Threw std::exception"); @@ -1087,13 +1215,14 @@ acutest_do_run_(const struct acutest_test_* test, int index) printf("C++ exception.\n\n"); } } +#endif #endif acutest_fini_(test->name); acutest_case_(NULL); acutest_current_test_ = NULL; - return status; + return state; } /* Trigger the unit test. If possible (and not suppressed) it starts a child @@ -1102,7 +1231,7 @@ acutest_do_run_(const struct acutest_test_* test, int index) static void acutest_run_(const struct acutest_test_* test, int index, int master_index) { - int failed = 1; + enum acutest_state_ state = ACUTEST_STATE_FAILED; acutest_timer_type_ start, end; acutest_current_test_ = test; @@ -1123,21 +1252,16 @@ acutest_run_(const struct acutest_test_* test, int index, int master_index) pid = fork(); if(pid == (pid_t)-1) { acutest_error_("Cannot fork. %s [%d]", strerror(errno), errno); - failed = 1; } else if(pid == 0) { /* Child: Do the test. */ acutest_worker_ = 1; - failed = (acutest_do_run_(test, index) != 0); - acutest_exit_(failed ? 1 : 0); + state = acutest_do_run_(test, index); + acutest_exit_((int) state); } else { /* Parent: Wait until child terminates and analyze its exit code. */ waitpid(pid, &exit_code, 0); if(WIFEXITED(exit_code)) { - switch(WEXITSTATUS(exit_code)) { - case 0: failed = 0; break; /* test has passed. */ - case 1: /* noop */ break; /* "normal" failure. */ - default: acutest_error_("Unexpected exit code [%d]", WEXITSTATUS(exit_code)); - } + state = (enum acutest_state_) WEXITSTATUS(exit_code); } else if(WIFSIGNALED(exit_code)) { char tmp[32]; const char* signame; @@ -1150,7 +1274,7 @@ acutest_run_(const struct acutest_test_* test, int index, int master_index) case SIGSEGV: signame = "SIGSEGV"; break; case SIGILL: signame = "SIGILL"; break; case SIGTERM: signame = "SIGTERM"; break; - default: sprintf(tmp, "signal %d", WTERMSIG(exit_code)); signame = tmp; break; + default: snprintf(tmp, sizeof(tmp), "signal %d", WTERMSIG(exit_code)); signame = tmp; break; } acutest_error_("Test interrupted by %s.", signame); } else { @@ -1167,7 +1291,7 @@ acutest_run_(const struct acutest_test_* test, int index, int master_index) /* Windows has no fork(). So we propagate all info into the child * through a command line arguments. */ - _snprintf(buffer, sizeof(buffer)-1, + snprintf(buffer, sizeof(buffer), "%s --worker=%d %s --no-exec --no-summary %s --verbose=%d --color=%s -- \"%s\"", acutest_argv0_, index, acutest_timer_ ? "--time" : "", acutest_tap_ ? "--tap" : "", acutest_verbose_level_, @@ -1180,40 +1304,35 @@ acutest_run_(const struct acutest_test_* test, int index, int master_index) GetExitCodeProcess(processInfo.hProcess, &exitCode); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); - failed = (exitCode != 0); - if(exitCode > 1) { - switch(exitCode) { - case 3: acutest_error_("Aborted."); break; - case 0xC0000005: acutest_error_("Access violation."); break; - default: acutest_error_("Test ended in an unexpected way [%lu].", exitCode); break; - } + switch(exitCode) { + case 0: state = ACUTEST_STATE_SUCCESS; break; + case 1: state = ACUTEST_STATE_FAILED; break; + case 2: state = ACUTEST_STATE_SKIPPED; break; + case 3: acutest_error_("Aborted."); break; + case 0xC0000005: acutest_error_("Access violation."); break; + default: acutest_error_("Test ended in an unexpected way [%lu].", exitCode); break; } } else { acutest_error_("Cannot create unit test subprocess [%ld].", GetLastError()); - failed = 1; } #else /* A platform where we don't know how to run child process. */ - failed = (acutest_do_run_(test, index) != 0); + state = acutest_do_run_(test, index); #endif } else { /* Child processes suppressed through --no-exec. */ - failed = (acutest_do_run_(test, index) != 0); + state = acutest_do_run_(test, index); } acutest_timer_get_time_(&end); acutest_current_test_ = NULL; - acutest_stat_run_units_++; - if(failed) - acutest_stat_failed_units_++; - - acutest_set_success_(master_index, !failed); - acutest_set_duration_(master_index, acutest_timer_diff_(start, end)); + acutest_test_data_[master_index].state = state; + acutest_test_data_[master_index].duration = acutest_timer_diff_(start, end); } #if defined(ACUTEST_WIN_) @@ -1250,8 +1369,8 @@ typedef struct acutest_test_CMDLINE_OPTION_ { static int acutest_cmdline_handle_short_opt_group_(const ACUTEST_CMDLINE_OPTION_* options, - const char* arggroup, - int (*callback)(int /*optval*/, const char* /*arg*/)) + const char* arggroup, + int (*callback)(int /*optval*/, const char* /*arg*/)) { const ACUTEST_CMDLINE_OPTION_* opt; int i; @@ -1272,7 +1391,7 @@ acutest_cmdline_handle_short_opt_group_(const ACUTEST_CMDLINE_OPTION_* options, badoptname[1] = arggroup[i]; badoptname[2] = '\0'; ret = callback((opt->id != 0 ? ACUTEST_CMDLINE_OPTID_MISSINGARG_ : ACUTEST_CMDLINE_OPTID_UNKNOWN_), - badoptname); + badoptname); } if(ret != 0) @@ -1325,7 +1444,7 @@ acutest_cmdline_read_(const ACUTEST_CMDLINE_OPTION_* options, int argc, char** a if(opt->flags & (ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ | ACUTEST_CMDLINE_OPTFLAG_REQUIREDARG_)) { ret = callback(opt->id, argv[i]+2+len+1); } else { - sprintf(auxbuf, "--%s", opt->longname); + snprintf(auxbuf, sizeof(auxbuf), "--%s", opt->longname); ret = callback(ACUTEST_CMDLINE_OPTID_BOGUSARG_, auxbuf); } break; @@ -1369,7 +1488,7 @@ acutest_cmdline_read_(const ACUTEST_CMDLINE_OPTION_* options, int argc, char** a /* Strip any argument from the long option. */ char* assignment = strchr(badoptname, '='); if(assignment != NULL) { - size_t len = assignment - badoptname; + size_t len = (size_t)(assignment - badoptname); if(len > ACUTEST_CMDLINE_AUXBUF_SIZE_) len = ACUTEST_CMDLINE_AUXBUF_SIZE_; strncpy(auxbuf, badoptname, len); @@ -1396,12 +1515,12 @@ acutest_help_(void) { printf("Usage: %s [options] [test...]\n", acutest_argv0_); printf("\n"); - printf("Run the specified unit tests; or if the option '--skip' is used, run all\n"); + printf("Run the specified unit tests; or if the option '--exclude' is used, run all\n"); printf("tests in the suite but those listed. By default, if no tests are specified\n"); printf("on the command line, all unit tests in the suite are run.\n"); printf("\n"); printf("Options:\n"); - printf(" -s, --skip Execute all unit tests but the listed ones\n"); + printf(" -X, --exclude Execute all unit tests but the listed ones\n"); printf(" --exec[=WHEN] If supported, execute unit tests as child processes\n"); printf(" (WHEN is one of 'auto', 'always', 'never')\n"); printf(" -E, --no-exec Same as --exec=never\n"); @@ -1436,35 +1555,36 @@ acutest_help_(void) } static const ACUTEST_CMDLINE_OPTION_ acutest_cmdline_options_[] = { - { 's', "skip", 's', 0 }, - { 0, "exec", 'e', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, - { 'E', "no-exec", 'E', 0 }, + { 'X', "exclude", 'X', 0 }, + { 's', "skip", 'X', 0 }, /* kept for compatibility, use --exclude instead */ + { 0, "exec", 'e', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, + { 'E', "no-exec", 'E', 0 }, #if defined ACUTEST_WIN_ - { 't', "time", 't', 0 }, + { 't', "time", 't', 0 }, { 0, "timer", 't', 0 }, /* kept for compatibility */ #elif defined ACUTEST_HAS_POSIX_TIMER_ - { 't', "time", 't', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, - { 0, "timer", 't', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, /* kept for compatibility */ + { 't', "time", 't', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, + { 0, "timer", 't', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, /* kept for compatibility */ #endif - { 0, "no-summary", 'S', 0 }, - { 0, "tap", 'T', 0 }, - { 'l', "list", 'l', 0 }, - { 'v', "verbose", 'v', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, - { 'q', "quiet", 'q', 0 }, - { 0, "color", 'c', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, - { 0, "no-color", 'C', 0 }, - { 'h', "help", 'h', 0 }, - { 0, "worker", 'w', ACUTEST_CMDLINE_OPTFLAG_REQUIREDARG_ }, /* internal */ - { 'x', "xml-output", 'x', ACUTEST_CMDLINE_OPTFLAG_REQUIREDARG_ }, - { 0, NULL, 0, 0 } + { 0, "no-summary", 'S', 0 }, + { 0, "tap", 'T', 0 }, + { 'l', "list", 'l', 0 }, + { 'v', "verbose", 'v', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, + { 'q', "quiet", 'q', 0 }, + { 0, "color", 'c', ACUTEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, + { 0, "no-color", 'C', 0 }, + { 'h', "help", 'h', 0 }, + { 0, "worker", 'w', ACUTEST_CMDLINE_OPTFLAG_REQUIREDARG_ }, /* internal */ + { 'x', "xml-output", 'x', ACUTEST_CMDLINE_OPTFLAG_REQUIREDARG_ }, + { 0, NULL, 0, 0 } }; static int acutest_cmdline_callback_(int id, const char* arg) { switch(id) { - case 's': - acutest_skip_mode_ = 1; + case 'X': + acutest_exclude_mode_ = 1; break; case 'e': @@ -1489,10 +1609,10 @@ acutest_cmdline_callback_(int id, const char* arg) #if defined ACUTEST_WIN_ || defined ACUTEST_HAS_POSIX_TIMER_ if(arg == NULL || strcmp(arg, "real") == 0) { acutest_timer_ = 1; -#ifndef ACUTEST_WIN_ + #ifndef ACUTEST_WIN_ } else if(strcmp(arg, "cpu") == 0) { acutest_timer_ = 2; -#endif + #endif } else { fprintf(stderr, "%s: Unrecognized argument '%s' for option --time.\n", acutest_argv0_, arg); fprintf(stderr, "Try '%s --help' for more information.\n", acutest_argv0_); @@ -1558,7 +1678,7 @@ acutest_cmdline_callback_(int id, const char* arg) break; case 0: - if(acutest_lookup_(arg) == 0) { + if(acutest_select_(arg) == 0) { fprintf(stderr, "%s: Unrecognized unit test '%s'\n", acutest_argv0_, arg); fprintf(stderr, "Try '%s --list' for list of unit tests.\n", acutest_argv0_); acutest_exit_(2); @@ -1587,100 +1707,114 @@ acutest_cmdline_callback_(int id, const char* arg) return 0; } - -#ifdef ACUTEST_LINUX_ static int -acutest_is_tracer_present_(void) +acutest_under_debugger_(void) { - /* Must be large enough so the line 'TracerPid: ${PID}' can fit in. */ - static const int OVERLAP = 32; +#ifdef ACUTEST_LINUX_ + /* Scan /proc/self/status for line "TracerPid: [PID]". If such line exists + * and the PID is non-zero, we're being debugged. */ + { + static const int OVERLAP = 32; + int fd; + char buf[512]; + size_t n_read; + pid_t tracer_pid = 0; - char buf[512]; - int tracer_present = 0; - int fd; - size_t n_read = 0; + /* Little trick so that we can treat the 1st line the same as any other + * and detect line start easily. */ + buf[0] = '\n'; + n_read = 1; - fd = open("/proc/self/status", O_RDONLY); - if(fd == -1) - return 0; + fd = open("/proc/self/status", O_RDONLY); + if(fd != -1) { + while(1) { + static const char pattern[] = "\nTracerPid:"; + const char* field; - while(1) { - static const char pattern[] = "TracerPid:"; - const char* field; + while(n_read < sizeof(buf) - 1) { + ssize_t n; - while(n_read < sizeof(buf) - 1) { - ssize_t n; + n = read(fd, buf + n_read, sizeof(buf) - 1 - n_read); + if(n <= 0) + break; + n_read += (size_t)n; + } + buf[n_read] = '\0'; - n = read(fd, buf + n_read, sizeof(buf) - 1 - n_read); - if(n <= 0) - break; - n_read += n; - } - buf[n_read] = '\0'; + field = strstr(buf, pattern); + if(field != NULL && field < buf + sizeof(buf) - OVERLAP) { + tracer_pid = (pid_t) atoi(field + sizeof(pattern) - 1); + break; + } - field = strstr(buf, pattern); - if(field != NULL && field < buf + sizeof(buf) - OVERLAP) { - pid_t tracer_pid = (pid_t) atoi(field + sizeof(pattern) - 1); - tracer_present = (tracer_pid != 0); - break; - } + if(n_read == sizeof(buf) - 1) { + /* Move the tail with the potentially incomplete line we're + * be looking for to the beginning of the buffer. + * (The OVERLAP must be large enough so the searched line + * can fit in completely.) */ + memmove(buf, buf + sizeof(buf) - 1 - OVERLAP, OVERLAP); + n_read = OVERLAP; + } else { + break; + } + } - if(n_read == sizeof(buf) - 1) { - /* Move the tail with the potentially incomplete line we're looking - * for to the beginning of the buffer. */ - memmove(buf, buf + sizeof(buf) - 1 - OVERLAP, OVERLAP); - n_read = OVERLAP; - } else { - break; + close(fd); + + if(tracer_pid != 0) + return 1; } } - - close(fd); - return tracer_present; -} #endif #ifdef ACUTEST_MACOS_ -static bool -acutest_AmIBeingDebugged(void) -{ - int junk; - int mib[4]; - struct kinfo_proc info; - size_t size; + /* See https://developer.apple.com/library/archive/qa/qa1361/_index.html */ + { + int mib[4]; + struct kinfo_proc info; + size_t size; - // Initialize the flags so that, if sysctl fails for some bizarre - // reason, we get a predictable result. - info.kp_proc.p_flag = 0; + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PID; + mib[3] = getpid(); - // Initialize mib, which tells sysctl the info we want, in this case - // we're looking for information about a specific process ID. - mib[0] = CTL_KERN; - mib[1] = KERN_PROC; - mib[2] = KERN_PROC_PID; - mib[3] = getpid(); + size = sizeof(info); + info.kp_proc.p_flag = 0; + sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0); - // Call sysctl. - size = sizeof(info); - junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0); - assert(junk == 0); - - // We're being debugged if the P_TRACED flag is set. - return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); -} + if(info.kp_proc.p_flag & P_TRACED) + return 1; + } #endif +#ifdef ACUTEST_WIN_ + if(IsDebuggerPresent()) + return 1; +#endif + +#ifdef RUNNING_ON_VALGRIND + /* We treat Valgrind as a debugger of sorts. + * (Macro RUNNING_ON_VALGRIND is provided by , if available.) */ + if(RUNNING_ON_VALGRIND) + return 1; +#endif + + return 0; +} + int main(int argc, char** argv) { - int i; + int i, index; + int exit_code = 1; acutest_argv0_ = argv[0]; #if defined ACUTEST_UNIX_ acutest_colorize_ = isatty(STDOUT_FILENO); #elif defined ACUTEST_WIN_ - #if defined _BORLANDC_ + #if defined _BORLANDC_ acutest_colorize_ = isatty(_fileno(stdout)); #else acutest_colorize_ = _isatty(_fileno(stdout)); @@ -1713,37 +1847,39 @@ main(int argc, char** argv) #endif #endif - /* By default, we want to run all tests. */ - if(acutest_count_ == 0) { + /* Determine what to run. */ + if(acutest_count_(ACUTEST_STATE_SELECTED) > 0) { + enum acutest_state_ if_selected; + enum acutest_state_ if_unselected; + + if(!acutest_exclude_mode_) { + if_selected = ACUTEST_STATE_NEEDTORUN; + if_unselected = ACUTEST_STATE_EXCLUDED; + } else { + if_selected = ACUTEST_STATE_EXCLUDED; + if_unselected = ACUTEST_STATE_NEEDTORUN; + } + + for(i = 0; acutest_list_[i].func != NULL; i++) { + if(acutest_test_data_[i].state == ACUTEST_STATE_SELECTED) + acutest_test_data_[i].state = if_selected; + else + acutest_test_data_[i].state = if_unselected; + } + } else { + /* By default, we want to run all tests. */ for(i = 0; acutest_list_[i].func != NULL; i++) - acutest_remember_(i); + acutest_test_data_[i].state = ACUTEST_STATE_NEEDTORUN; } - /* Guess whether we want to run unit tests as child processes. */ + /* By default, we want to suppress running tests as child processes if we + * run just one test, or if we're under debugger: Debugging tests is then + * so much easier. */ if(acutest_no_exec_ < 0) { - acutest_no_exec_ = 0; - - if(acutest_count_ <= 1) { + if(acutest_count_(ACUTEST_STATE_NEEDTORUN) <= 1 || acutest_under_debugger_()) acutest_no_exec_ = 1; - } else { -#ifdef ACUTEST_WIN_ - if(IsDebuggerPresent()) - acutest_no_exec_ = 1; -#endif -#ifdef ACUTEST_LINUX_ - if(acutest_is_tracer_present_()) - acutest_no_exec_ = 1; -#endif -#ifdef ACUTEST_MACOS_ - if(acutest_AmIBeingDebugged()) - acutest_no_exec_ = 1; -#endif -#ifdef RUNNING_ON_VALGRIND - /* RUNNING_ON_VALGRIND is provided by optionally included */ - if(RUNNING_ON_VALGRIND) - acutest_no_exec_ = 1; -#endif - } + else + acutest_no_exec_ = 0; } if(acutest_tap_) { @@ -1757,37 +1893,38 @@ main(int argc, char** argv) acutest_no_summary_ = 1; if(!acutest_worker_) - printf("1..%d\n", (int) acutest_count_); + printf("1..%d\n", acutest_count_(ACUTEST_STATE_NEEDTORUN)); } - int index = acutest_worker_index_; + index = acutest_worker_index_; for(i = 0; acutest_list_[i].func != NULL; i++) { - int run = (acutest_test_data_[i].flags & ACUTEST_FLAG_RUN_); - if (acutest_skip_mode_) /* Run all tests except those listed. */ - run = !run; - if(run) + if(acutest_test_data_[i].state == ACUTEST_STATE_NEEDTORUN) acutest_run_(´st_list_[i], index++, i); } /* Write a summary */ if(!acutest_no_summary_ && acutest_verbose_level_ >= 1) { + int n_run, n_success, n_failed ; + + n_run = acutest_list_size_ - acutest_count_(ACUTEST_STATE_EXCLUDED); + n_success = acutest_count_(ACUTEST_STATE_SUCCESS); + n_failed = acutest_count_(ACUTEST_STATE_FAILED); + if(acutest_verbose_level_ >= 3) { acutest_colored_printf_(ACUTEST_COLOR_DEFAULT_INTENSIVE_, "Summary:\n"); - printf(" Count of all unit tests: %4d\n", (int) acutest_list_size_); - printf(" Count of run unit tests: %4d\n", acutest_stat_run_units_); - printf(" Count of failed unit tests: %4d\n", acutest_stat_failed_units_); - printf(" Count of skipped unit tests: %4d\n", (int) acutest_list_size_ - acutest_stat_run_units_); + printf(" Count of run unit tests: %4d\n", n_run); + printf(" Count of successful unit tests: %4d\n", n_success); + printf(" Count of failed unit tests: %4d\n", n_failed); } - if(acutest_stat_failed_units_ == 0) { + if(n_failed == 0) { acutest_colored_printf_(ACUTEST_COLOR_GREEN_INTENSIVE_, "SUCCESS:"); - printf(" All unit tests have passed.\n"); + printf(" No unit tests have failed.\n"); } else { acutest_colored_printf_(ACUTEST_COLOR_RED_INTENSIVE_, "FAILED:"); printf(" %d of %d unit tests %s failed.\n", - acutest_stat_failed_units_, acutest_stat_run_units_, - (acutest_stat_failed_units_ == 1) ? "has" : "have"); + n_failed, n_run, (n_failed == 1) ? "has" : "have"); } if(acutest_verbose_level_ >= 3) @@ -1795,45 +1932,63 @@ main(int argc, char** argv) } if (acutest_xml_output_) { -#if defined ACUTEST_UNIX_ - char *suite_name = basename(argv[0]); -#elif defined ACUTEST_WIN_ - char suite_name[_MAX_FNAME]; - _splitpath(argv[0], NULL, NULL, suite_name, NULL); -#else - const char *suite_name = argv[0]; -#endif + const char* suite_name = acutest_basename_(argv[0]); fprintf(acutest_xml_output_, "\n"); - fprintf(acutest_xml_output_, "\n", - suite_name, (int)acutest_list_size_, acutest_stat_failed_units_, acutest_stat_failed_units_, - (int)acutest_list_size_ - acutest_stat_run_units_); + fprintf(acutest_xml_output_, "\n", + suite_name, + (int)acutest_list_size_, + acutest_count_(ACUTEST_STATE_FAILED), + acutest_count_(ACUTEST_STATE_SKIPPED) + acutest_count_(ACUTEST_STATE_EXCLUDED)); for(i = 0; acutest_list_[i].func != NULL; i++) { struct acutest_test_data_ *details = ´st_test_data_[i]; + const char* str_state; fprintf(acutest_xml_output_, " \n", acutest_list_[i].name, details->duration); - if (details->flags & ACUTEST_FLAG_FAILURE_) - fprintf(acutest_xml_output_, " \n"); - if (!(details->flags & ACUTEST_FLAG_FAILURE_) && !(details->flags & ACUTEST_FLAG_SUCCESS_)) - fprintf(acutest_xml_output_, " \n"); + + switch(details->state) { + case ACUTEST_STATE_SUCCESS: str_state = NULL; break; + case ACUTEST_STATE_EXCLUDED: /* Fall through. */ + case ACUTEST_STATE_SKIPPED: str_state = ""; break; + case ACUTEST_STATE_FAILED: /* Fall through. */ + default: str_state = ""; break; + } + + if(str_state != NULL) + fprintf(acutest_xml_output_, " %s\n", str_state); fprintf(acutest_xml_output_, " \n"); } fprintf(acutest_xml_output_, "\n"); fclose(acutest_xml_output_); } - acutest_cleanup_(); + if(acutest_worker_ && acutest_count_(ACUTEST_STATE_EXCLUDED)+1 == acutest_list_size_) { + /* If we are the child process, we need to propagate the test state + * without any moderation. */ + for(i = 0; acutest_list_[i].func != NULL; i++) { + if(acutest_test_data_[i].state != ACUTEST_STATE_EXCLUDED) { + exit_code = (int) acutest_test_data_[i].state; + break; + } + } + } else { + if(acutest_count_(ACUTEST_STATE_FAILED) > 0) + exit_code = 1; + else + exit_code = 0; + } - return (acutest_stat_failed_units_ == 0) ? 0 : 1; + acutest_cleanup_(); + return exit_code; } #endif /* #ifndef TEST_NO_MAIN */ #ifdef _MSC_VER -#pragma warning(pop) + #pragma warning(pop) #endif #ifdef __cplusplus -} /* extern "C" */ + } /* extern "C" */ #endif #endif /* #ifndef ACUTEST_H */ diff --git a/test/routing.c b/test/lnm/routing.c similarity index 94% rename from test/routing.c rename to test/lnm/routing.c index 827d4c5..921dc81 100644 --- a/test/routing.c +++ b/test/lnm/routing.c @@ -1,8 +1,9 @@ +#define TEST_NO_MAIN +#include "acutest.h" +#include "tests.h" + #include "lnm/common.h" #include "lnm/http/route.h" -#include "test.h" - -#include "lnm/http/loop.h" void test_routing_simple() { lnm_http_router *router; @@ -101,11 +102,3 @@ void test_routing_nest() { lnm_http_router_free(r2); } - -TEST_LIST = { - { "routing simple", test_routing_simple }, - { "routing star", test_routing_star }, - { "routing merge", test_routing_merge }, - { "routing nest", test_routing_nest }, - { NULL, NULL } -}; diff --git a/test/runner.c b/test/runner.c new file mode 100644 index 0000000..9fe31c0 --- /dev/null +++ b/test/runner.c @@ -0,0 +1,10 @@ +#include "acutest.h" +#include "tests.h" + +TEST_LIST = { + { "routing simple", test_routing_simple }, + { "routing star", test_routing_star }, + { "routing merge", test_routing_merge }, + { "routing nest", test_routing_nest }, + { NULL, NULL } +}; diff --git a/test/tests.h b/test/tests.h new file mode 100644 index 0000000..f5ebcdc --- /dev/null +++ b/test/tests.h @@ -0,0 +1,9 @@ +#ifndef TEST_TESTS +#define TEST_TESTS + +void test_routing_simple(); +void test_routing_star(); +void test_routing_merge(); +void test_routing_nest(); + +#endif From 0e39ce3618f2fe0bf39b09652de45a45e7440165 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Sat, 30 Mar 2024 11:46:49 +0100 Subject: [PATCH 20/21] chore: refactor repository for cleaner development --- Makefile | 45 +++++++++------------- config.mk | 3 +- {include => src/_include}/picohttpparser.h | 0 src/{ => lnm}/http/lnm_http_consts.c | 0 src/{ => lnm}/http/lnm_http_loop.c | 0 src/{ => lnm}/http/lnm_http_loop_ctx.c | 0 src/{ => lnm}/http/lnm_http_loop_process.c | 0 src/{ => lnm}/http/lnm_http_loop_steps.c | 0 src/{ => lnm}/http/lnm_http_req.c | 0 src/{ => lnm}/http/lnm_http_res.c | 0 src/{ => lnm}/http/lnm_http_route.c | 0 src/{ => lnm}/http/lnm_http_router.c | 0 src/{ => lnm}/lnm_log.c | 0 src/{ => lnm}/lnm_utils.c | 0 src/{ => lnm}/loop/lnm_loop.c | 0 src/{ => lnm}/loop/lnm_loop_conn.c | 0 src/{ => lnm}/loop/lnm_loop_io.c | 0 src/{ => lnm}/loop/lnm_loop_worker.c | 0 18 files changed, 19 insertions(+), 29 deletions(-) rename {include => src/_include}/picohttpparser.h (100%) rename src/{ => lnm}/http/lnm_http_consts.c (100%) rename src/{ => lnm}/http/lnm_http_loop.c (100%) rename src/{ => lnm}/http/lnm_http_loop_ctx.c (100%) rename src/{ => lnm}/http/lnm_http_loop_process.c (100%) rename src/{ => lnm}/http/lnm_http_loop_steps.c (100%) rename src/{ => lnm}/http/lnm_http_req.c (100%) rename src/{ => lnm}/http/lnm_http_res.c (100%) rename src/{ => lnm}/http/lnm_http_route.c (100%) rename src/{ => lnm}/http/lnm_http_router.c (100%) rename src/{ => lnm}/lnm_log.c (100%) rename src/{ => lnm}/lnm_utils.c (100%) rename src/{ => lnm}/loop/lnm_loop.c (100%) rename src/{ => lnm}/loop/lnm_loop_conn.c (100%) rename src/{ => lnm}/loop/lnm_loop_io.c (100%) rename src/{ => lnm}/loop/lnm_loop_worker.c (100%) diff --git a/Makefile b/Makefile index 9041b06..914c089 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ -include config.mk -LIB := $(BUILD_DIR)/$(LIB_FILENAME) +LIB_ARCHIVE := $(BUILD_DIR)/lib$(LIB).a SRCS != find '$(SRC_DIR)' -iname '*.c' SRCS_H != find include -iname '*.h' @@ -20,26 +20,17 @@ DEPS := $(SRCS:%=$(BUILD_DIR)/%.d) $(SRCS_TEST:%=$(BUILD_DIR)/%.d) BIN_TEST := $(BUILD_DIR)/$(TEST_DIR)/runner BINS_EXAMPLE := $(OBJS_EXAMPLE:%.c.o=%) -TARGETS_TEST := $(BINS_TEST:%=test-%) -TARGETS_MEM_TEST := $(BINS_TEST:%=test-mem-%) -TARGETS_EXAMPLE := $(BINS_EXAMPLE:%=example-%) - _CFLAGS := $(addprefix -I,$(INC_DIRS)) $(CFLAGS) -Wall -Wextra -.PHONY: all -all: lib - - # =====COMPILATION===== # Utility used by the CI to lint +.PHONY: lib +$(LIB_ARCHIVE): $(OBJS) + ar -rcs $@ $^ + .PHONY: objs objs: $(OBJS) -.PHONY: lib -lib: $(LIB) -$(LIB): $(OBJS) - ar -rcs $@ $(OBJS) - $(BUILD_DIR)/$(SRC_DIR)/%.c.o: $(SRC_DIR)/%.c mkdir -p $(dir $@) $(CC) -c $(_CFLAGS) $< -o $@ @@ -56,7 +47,7 @@ test-mem: $(BIN_TEST) .PHONY: build-test build-test: $(BIN_TEST) -$(BIN_TEST): $(OBJS_TEST) $(LIB) +$(BIN_TEST): $(OBJS_TEST) $(LIB_ARCHIVE) $(CC) -o $@ $^ $(_LDFLAGS) # Along with the include directory, each test includes $(TEST_DIR) (which @@ -73,7 +64,7 @@ $(BUILD_DIR)/$(TEST_DIR)/%.c.o: $(TEST_DIR)/%.c .PHONY: build-example build-example: $(BINS_EXAMPLE) -$(BINS_EXAMPLE): %: %.c.o $(LIB) +$(BINS_EXAMPLE): %: %.c.o $(LIB_ARCHIVE) $(CC) $(LDFLAGS) \ $^ -o $@ @@ -85,22 +76,22 @@ $(BUILD_DIR)/$(EXAMPLE_DIR)/%.c.o: $(EXAMPLE_DIR)/%.c # =====MAINTENANCE===== .PHONY: lint lint: - clang-format -n --Werror \ - $(filter-out $(THIRDPARTY),$(SRCS)) \ - $(filter-out $(THIRDPARTY),$(SRCS_H)) \ - $(filter-out $(THIRDPARTY),$(SRCS_H_INTERNAL)) + @ clang-format -n --Werror \ + $(shell find '$(SRC_DIR)/$(LIB)' -iname '*.c') \ + $(shell find '$(SRC_DIR)/_include/$(LIB)' -iname '*.h') \ + $(shell find 'include/$(LIB)' -iname '*.h') .PHONY: fmt fmt: - clang-format -i \ - $(filter-out $(THIRDPARTY),$(SRCS)) \ - $(filter-out $(THIRDPARTY),$(SRCS_H)) \ - $(filter-out $(THIRDPARTY),$(SRCS_H_INTERNAL)) + @ clang-format -i \ + $(shell find '$(SRC_DIR)/$(LIB)' -iname '*.c') \ + $(shell find '$(SRC_DIR)/_include/$(LIB)' -iname '*.h') \ + $(shell find 'include/$(LIB)' -iname '*.h') .PHONY: check check: - mkdir -p $(BUILD_DIR)/cppcheck - cppcheck \ + @ mkdir -p $(BUILD_DIR)/cppcheck + @ cppcheck \ $(addprefix -I,$(INC_DIRS)) \ --cppcheck-build-dir=$(BUILD_DIR)/cppcheck \ --error-exitcode=1 \ @@ -109,7 +100,7 @@ check: --check-level=exhaustive \ --quiet \ -j$(shell nproc) \ - $(filter-out $(THIRDPARTY),$(SRCS)) + $(shell find '$(SRC_DIR)/$(LIB)' -iname '*.c') .PHONY: clean clean: diff --git a/config.mk b/config.mk index 4345382..96d73b9 100644 --- a/config.mk +++ b/config.mk @@ -1,10 +1,9 @@ -LIB_FILENAME = liblnm.a +LIB = lnm BUILD_DIR = build SRC_DIR = src TEST_DIR = test EXAMPLE_DIR = example -THIRDPARTY = src/picohttpparser.c include/picohttpparser.h PUB_INC_DIR = include INC_DIRS = $(PUB_INC_DIR) src/_include diff --git a/include/picohttpparser.h b/src/_include/picohttpparser.h similarity index 100% rename from include/picohttpparser.h rename to src/_include/picohttpparser.h diff --git a/src/http/lnm_http_consts.c b/src/lnm/http/lnm_http_consts.c similarity index 100% rename from src/http/lnm_http_consts.c rename to src/lnm/http/lnm_http_consts.c diff --git a/src/http/lnm_http_loop.c b/src/lnm/http/lnm_http_loop.c similarity index 100% rename from src/http/lnm_http_loop.c rename to src/lnm/http/lnm_http_loop.c diff --git a/src/http/lnm_http_loop_ctx.c b/src/lnm/http/lnm_http_loop_ctx.c similarity index 100% rename from src/http/lnm_http_loop_ctx.c rename to src/lnm/http/lnm_http_loop_ctx.c diff --git a/src/http/lnm_http_loop_process.c b/src/lnm/http/lnm_http_loop_process.c similarity index 100% rename from src/http/lnm_http_loop_process.c rename to src/lnm/http/lnm_http_loop_process.c diff --git a/src/http/lnm_http_loop_steps.c b/src/lnm/http/lnm_http_loop_steps.c similarity index 100% rename from src/http/lnm_http_loop_steps.c rename to src/lnm/http/lnm_http_loop_steps.c diff --git a/src/http/lnm_http_req.c b/src/lnm/http/lnm_http_req.c similarity index 100% rename from src/http/lnm_http_req.c rename to src/lnm/http/lnm_http_req.c diff --git a/src/http/lnm_http_res.c b/src/lnm/http/lnm_http_res.c similarity index 100% rename from src/http/lnm_http_res.c rename to src/lnm/http/lnm_http_res.c diff --git a/src/http/lnm_http_route.c b/src/lnm/http/lnm_http_route.c similarity index 100% rename from src/http/lnm_http_route.c rename to src/lnm/http/lnm_http_route.c diff --git a/src/http/lnm_http_router.c b/src/lnm/http/lnm_http_router.c similarity index 100% rename from src/http/lnm_http_router.c rename to src/lnm/http/lnm_http_router.c diff --git a/src/lnm_log.c b/src/lnm/lnm_log.c similarity index 100% rename from src/lnm_log.c rename to src/lnm/lnm_log.c diff --git a/src/lnm_utils.c b/src/lnm/lnm_utils.c similarity index 100% rename from src/lnm_utils.c rename to src/lnm/lnm_utils.c diff --git a/src/loop/lnm_loop.c b/src/lnm/loop/lnm_loop.c similarity index 100% rename from src/loop/lnm_loop.c rename to src/lnm/loop/lnm_loop.c diff --git a/src/loop/lnm_loop_conn.c b/src/lnm/loop/lnm_loop_conn.c similarity index 100% rename from src/loop/lnm_loop_conn.c rename to src/lnm/loop/lnm_loop_conn.c diff --git a/src/loop/lnm_loop_io.c b/src/lnm/loop/lnm_loop_io.c similarity index 100% rename from src/loop/lnm_loop_io.c rename to src/lnm/loop/lnm_loop_io.c diff --git a/src/loop/lnm_loop_worker.c b/src/lnm/loop/lnm_loop_worker.c similarity index 100% rename from src/loop/lnm_loop_worker.c rename to src/lnm/loop/lnm_loop_worker.c From f5c0db773378d550246bad384b887960fabf2ea0 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Sat, 6 Apr 2024 15:16:14 +0200 Subject: [PATCH 21/21] fix: proper va_end usage --- src/lnm/http/lnm_http_loop_process.c | 1 - src/lnm/lnm_log.c | 5 ++++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/lnm/http/lnm_http_loop_process.c b/src/lnm/http/lnm_http_loop_process.c index ea690ce..4f6871f 100644 --- a/src/lnm/http/lnm_http_loop_process.c +++ b/src/lnm/http/lnm_http_loop_process.c @@ -8,7 +8,6 @@ #include "lnm/http/req.h" #include "lnm/log.h" #include "lnm/loop.h" -#include "lnm/loop_internal.h" static const char *section = "http"; diff --git a/src/lnm/lnm_log.c b/src/lnm/lnm_log.c index 15fb00f..c27a876 100644 --- a/src/lnm/lnm_log.c +++ b/src/lnm/lnm_log.c @@ -65,6 +65,9 @@ void lnm_vlog(lnm_log_level level, const char *section, const char *fmt, continue; } + va_list aq; + va_copy(aq, ap); + switch (stream->type) { case lnm_logger_stream_type_file: fprintf(stream->ptr, "[%s][%s][%s] ", date_str, @@ -74,7 +77,7 @@ void lnm_vlog(lnm_log_level level, const char *section, const char *fmt, break; } - va_end(ap); + va_end(aq); } }