add router

This commit is contained in:
Dennis Eichhorn 2022-11-20 20:37:17 +01:00
parent b8a9750feb
commit a6216bdb58
2 changed files with 73 additions and 2 deletions

71
Router/Router.h Normal file
View File

@ -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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <regex>
#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

View File

@ -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) {