From a6216bdb586725637e85d5b57bca4a02b388d678 Mon Sep 17 00:00:00 2001 From: Dennis Eichhorn Date: Sun, 20 Nov 2022 20:37:17 +0100 Subject: [PATCH] add router --- Router/Router.h | 71 ++++++++++++++++++++++++++++++++++++++++++++++ Stdlib/HashTable.h | 4 +-- 2 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 Router/Router.h diff --git a/Router/Router.h b/Router/Router.h new file mode 100644 index 0000000..f7c5b63 --- /dev/null +++ b/Router/Router.h @@ -0,0 +1,71 @@ +/** + * Karaka + * + * @package Stdlib + * @copyright Dennis Eichhorn + * @license OMS License 1.0 + * @version 1.0.0 + * @link https://karaka.app + */ +#ifndef ROUTER_ROUTER_H +#define ROUTER_ROUTER_H + +#include +#include +#include + +#include +#include + +#include "../Stdlib/HashTable.h" +#include "../Hash/MeowHash.h" + +namespace Router +{ + typedef void (*Fptr)(int, char **); + + typedef struct { + Stdlib::HashTable::ht *routes; + } Router; + + Router create_router(int size) + { + Router router; + router.routes = Stdlib::HashTable::create_table(size, true); + + return router; + } + + void set(Router *router, const char* route, void *endpoint) + { + Stdlib::HashTable::set_entry(router->routes, route, endpoint); + } + + Fptr match_route(Router *router, const char *uri) + { + Fptr ptr = NULL; + Stdlib::HashTable::it itr = Stdlib::HashTable::table_iterator(router->routes); + + std::regex regex; + std::cmatch match; + + while (Stdlib::HashTable::next(&itr)) { + regex = std::regex(itr.key); + + bool status = std::regex_search(uri, match, regex); + if (status) { + ptr = (Fptr) itr.value; + } + } + + return ptr; + } + + void free_router(Router *router) + { + Stdlib::HashTable::free_table(router->routes); + router->routes = NULL; + } +} + +#endif \ No newline at end of file diff --git a/Stdlib/HashTable.h b/Stdlib/HashTable.h index c9ff2b7..3a7a2fb 100755 --- a/Stdlib/HashTable.h +++ b/Stdlib/HashTable.h @@ -74,7 +74,7 @@ namespace Stdlib void *get_entry(ht *table, const char *key) { unsigned long long hash = hash_key(key); - size_t index = (size_t)(hash & (unsigned long long)(table->max - 1)); + size_t index = (size_t) (hash & (unsigned long long)(table->max - 1)); while (table->entries[index].key != NULL) { if (strcmp(key, table->entries[index].key) == 0) { @@ -93,7 +93,7 @@ namespace Stdlib const char *_set_entry(entry *entries, size_t max, const char *key, void *value, size_t *size) { unsigned long long hash = hash_key(key); - size_t index = (size_t)(hash & (unsigned long long)(max - 1)); + size_t index = (size_t) (hash & (unsigned long long)(max - 1)); while (entries[index].key != NULL) { if (strcmp(key, entries[index].key) == 0) {