update hashmap library

This commit is contained in:
2025-08-01 23:45:29 +02:00
parent aedd51fb99
commit c7ad5d7874
8 changed files with 261 additions and 219 deletions

View File

@@ -34,7 +34,7 @@ typedef struct cws_http_t {
char location[CWS_HTTP_LOCATION_LEN]; /**< Resource requested */ char location[CWS_HTTP_LOCATION_LEN]; /**< Resource requested */
char location_path[CWS_HTTP_LOCATION_PATH_LEN]; /**< Full resource path */ char location_path[CWS_HTTP_LOCATION_PATH_LEN]; /**< Full resource path */
char http_version[CWS_HTTP_VERSION_LEN]; /**< HTTP version */ char http_version[CWS_HTTP_VERSION_LEN]; /**< HTTP version */
cws_hashmap *headers; /**< Headers hash map */ mcl_hashmap *headers; /**< Headers hash map */
} cws_http; } cws_http;
/* Connection */ /* Connection */
/* Accept-Encoding */ /* Accept-Encoding */

View File

@@ -22,14 +22,6 @@
/* Main server loop */ /* Main server loop */
extern volatile sig_atomic_t cws_server_run; extern volatile sig_atomic_t cws_server_run;
/**
* @brief Runs the server
*
* @param[in] config The server's config
* @return 0 on success, -1 on error
*/
int cws_server_start(cws_config *config);
/** /**
* @brief Setups hints object * @brief Setups hints object
* *
@@ -39,12 +31,20 @@ int cws_server_start(cws_config *config);
*/ */
void cws_server_setup_hints(struct addrinfo *hints, size_t len, const char *hostname); void cws_server_setup_hints(struct addrinfo *hints, size_t len, const char *hostname);
/**
* @brief Runs the server
*
* @param[in] config The server's config
* @return 0 on success, -1 on error
*/
int cws_server_start(cws_config *config);
/** /**
* @brief Main server loop * @brief Main server loop
* *
* @param[in,out] sockfd Socket of the commincation endpoint * @param[in,out] sockfd Socket of the commincation endpoint
*/ */
void cws_server_loop(int sockfd, cws_config *config); int cws_server_loop(int sockfd, cws_config *config);
/** /**
* @brief Adds a file descriptor to the interest list * @brief Adds a file descriptor to the interest list
@@ -53,7 +53,7 @@ void cws_server_loop(int sockfd, cws_config *config);
* @param[in] sockfd The file descriptor to watch * @param[in] sockfd The file descriptor to watch
* @param[in] events The events to follow * @param[in] events The events to follow
*/ */
void cws_epoll_add(int epfd, int sockfd, uint32_t events); int cws_epoll_add(int epfd, int sockfd, uint32_t events);
/** /**
* @brief Removes a file descriptor from the interest list * @brief Removes a file descriptor from the interest list
@@ -61,14 +61,14 @@ void cws_epoll_add(int epfd, int sockfd, uint32_t events);
* @param[in] epfd epoll file descriptor * @param[in] epfd epoll file descriptor
* @param[in] sockfd The file descriptor to remove * @param[in] sockfd The file descriptor to remove
*/ */
void cws_epoll_del(int epfd, int sockfd); int cws_epoll_del(int epfd, int sockfd);
/** /**
* @brief Makes a file descriptor non-blocking * @brief Makes a file descriptor non-blocking
* *
* @param[in] sockfd The file descriptor to make non-blocking * @param[in] sockfd The file descriptor to make non-blocking
*/ */
void cws_fd_set_nonblocking(int sockfd); int cws_fd_set_nonblocking(int sockfd);
/** /**
* @brief Handles the new client * @brief Handles the new client
@@ -87,10 +87,6 @@ int cws_server_accept_client(int sockfd, struct sockaddr_storage *their_sa, sock
* @param[in] client_fd Client file descriptor * @param[in] client_fd Client file descriptor
* @param[in] hashmap Clients hash map * @param[in] hashmap Clients hash map
*/ */
void cws_server_close_client(int epfd, int client_fd, cws_hashmap *hashmap); void cws_server_close_client(int epfd, int client_fd, mcl_hashmap *hashmap);
/* Undocumented functions */
SSL_CTX *cws_ssl_create_context();
bool cws_ssl_configure(SSL_CTX *context, cws_config *config);
#endif #endif

View File

@@ -1,26 +1,30 @@
#ifndef CWS_HASHMAP_H #ifndef MYCLIB_HASHMAP_H
#define CWS_HASHMAP_H #define MYCLIB_HASHMAP_H
#include <stdbool.h> #include <stdbool.h>
#include <stddef.h>
#define CWS_HASHMAP_SIZE 1024 /**< Number of buckets in the hash map */ #define MYCLIB_HASHMAP_SIZE 1024 /**< Number of buckets in the hash map */
/** /**
* @brief A single bucket in the hash map. * @brief A single bucket in the hash map
*
* Each bucket can hold one key-value pair and points to the next bucket
* in case of hash collisions (separate chaining).
*/ */
typedef struct cws_bucket_t { typedef struct mcl_bucket_t {
void *key; /**< Pointer to the key */ void *key; /**< Pointer to the key */
void *value; /**< Pointer to the value */ void *value; /**< Pointer to the value */
struct cws_bucket_t *next; /**< Pointer to the next bucket in case of collision */ struct mcl_bucket_t *next; /**< Pointer to the next bucket in case of collision */
} cws_bucket; } mcl_bucket;
/** /**
* @brief Function pointer type for a hash function * @brief Function pointer type for a hash function
* *
* @param[in] key Pointer to the key to hash * @param[in] key Pointer to the key to hash
* @return The computed hash as an integer * @return The computed hash as an unsigned integer
*/ */
typedef int cws_hash_fn(void *key); typedef unsigned int mcl_hash_fn(const void *key);
/** /**
* @brief Function pointer type for a key comparison function * @brief Function pointer type for a key comparison function
@@ -29,78 +33,95 @@ typedef int cws_hash_fn(void *key);
* @param[in] key_b Pointer to the second key * @param[in] key_b Pointer to the second key
* @return true if the keys are considered equal, false otherwise * @return true if the keys are considered equal, false otherwise
*/ */
typedef bool cws_equal_fn(void *key_a, void *key_b); typedef bool mcl_equal_fn(const void *key_a, const void *key_b);
/** /**
* @brief Function pointer type for freeing a key * @brief Function pointer type for freeing a key
* *
* @param[in] key Pointer to the key to free * @param[in] key Pointer to the key to free
*/ */
typedef void cws_free_key_fn(void *key); typedef void mcl_free_key_fn(void *key);
/** /**
* @brief Function pointer type for freeing a value * @brief Function pointer type for freeing a value
* *
* @param[in] value Pointer to the value to free * @param[in] value Pointer to the value to free
*/ */
typedef void cws_free_value_fn(void *value); typedef void mcl_free_value_fn(void *value);
/** /**
* @brief Main structure representing the hash map * @brief Main structure representing the hash map
*/
typedef struct cws_hashmap_t {
cws_hash_fn *hash_fn; /**< Hash function */
cws_equal_fn *equal_fn; /**< Equality comparison function */
cws_free_key_fn *free_key_fn; /**< Key deallocation function */
cws_free_value_fn *free_value_fn; /**< Value deallocation function */
cws_bucket map[CWS_HASHMAP_SIZE]; /**< Array of bucket chains */
} cws_hashmap;
/**
* @brief Initializes a new hash map with user-defined behavior
* *
* @param[in] hash_fn Function used to hash keys * Contains function pointers for hash computation, key comparison,
* @param[in] equal_fn Function used to compare keys * and memory management, along with the bucket array.
* @param[in] free_key_fn Function used to free keys
* @param[in] free_value_fn Function used to free values
* @return A pointer to the newly initialized hash map
*/ */
cws_hashmap *cws_hm_init(cws_hash_fn *hash_fn, cws_equal_fn *equal_fn, cws_free_key_fn *free_key_fn, cws_free_value_fn *free_value_fn); typedef struct mcl_hashmap_t {
mcl_hash_fn *hash_fn; /**< Hash function */
mcl_equal_fn *equal_fn; /**< Equality comparison function */
mcl_free_key_fn *free_key_fn; /**< Key deallocation function (optional) */
mcl_free_value_fn *free_value_fn; /**< Value deallocation function (optional) */
mcl_bucket map[MYCLIB_HASHMAP_SIZE]; /**< Array of bucket chains */
} mcl_hashmap;
/** /**
* @brief Frees all resources used by the hash map * @brief Initialize a new hash map with user-defined behavior functions
*
* Creates a new hash map and initializes it with the provided function pointers.
* The free functions can be NULL if no automatic memory management is needed.
*
* @param[in] hash_fn Function used to hash keys (required)
* @param[in] equal_fn Function used to compare keys (required)
* @param[in] free_key_fn Function used to free keys (optional, can be NULL)
* @param[in] free_value_fn Function used to free values (optional, can be NULL)
* @return A pointer to the newly initialized hash map, or NULL on failure
*/
mcl_hashmap *mcl_hm_init(mcl_hash_fn *hash_fn, mcl_equal_fn *equal_fn, mcl_free_key_fn *free_key_fn, mcl_free_value_fn *free_value_fn);
/**
* @brief Free all resources used by the hash map
*
* Iterates through all buckets, frees keys and values using the provided
* free functions (if not NULL), and deallocates the hash map structure.
* *
* @param[in] hashmap Pointer to the hash map to free * @param[in] hashmap Pointer to the hash map to free
*/ */
void cws_hm_free(cws_hashmap *hashmap); void mcl_hm_free(mcl_hashmap *hashmap);
/** /**
* @brief Inserts or updates a key-value pair in the hash map * @brief Insert or update a key-value pair in the hash map
*
* If the key already exists, the old value is freed (if free_value_fn is provided)
* and replaced with the new value. If the key doesn't exist, a new entry is created.
* *
* @param[in] hashmap Pointer to the hash map * @param[in] hashmap Pointer to the hash map
* @param[in] key Pointer to the key to insert * @param[in] key Pointer to the key to insert (must not be NULL)
* @param[in] value Pointer to the value to insert * @param[in] value Pointer to the value to insert (can be NULL)
* @return true if the operation succeeded, false otherwise * @return true if the operation succeeded, false on failure (NULL hashmap/key or memory allocation failure)
*/ */
bool cws_hm_set(cws_hashmap *hashmap, void *key, void *value); bool mcl_hm_set(mcl_hashmap *hashmap, void *key, void *value);
/** /**
* @brief Retrieves a bucket by key * @brief Retrieve a bucket by key
*
* Searches for the given key in the hash map and returns the bucket containing it.
* The caller can then access both the key and value from the returned bucket.
* *
* @param[in] hashmap Pointer to the hash map * @param[in] hashmap Pointer to the hash map
* @param[in] key Pointer to the key to search for * @param[in] key Pointer to the key to search for
* @return Pointer to the found bucket, or NULL if not found * @return Pointer to the found bucket, or NULL if not found or on invalid input
*/ */
cws_bucket *cws_hm_get(cws_hashmap *hashmap, void *key); mcl_bucket *mcl_hm_get(mcl_hashmap *hashmap, void *key);
/** /**
* @brief Removes a key-value pair from the hash map * @brief Remove a key-value pair from the hash map
*
* Searches for the given key and removes it from the hash map. Both the key
* and value are freed using the provided free functions (if not NULL).
* *
* @param[in] hashmap Pointer to the hash map * @param[in] hashmap Pointer to the hash map
* @param[in] key Pointer to the key to remove, this pointer will be freed so pay attention * @param[in] key Pointer to the key to remove
* @return False if the key is not found, otherwise true * @return true if the key was found and removed, false if not found or on invalid input
*/ */
bool cws_hm_remove(cws_hashmap *hashmap, void *key); bool mcl_hm_remove(mcl_hashmap *hashmap, void *key);
#endif #endif /* MYCLIB_HASHMAP_H */

View File

@@ -33,12 +33,12 @@ void cws_utils_get_client_ip(struct sockaddr_storage *sa, char *ip);
char *cws_strip(char *str); char *cws_strip(char *str);
/* Functions used for hash maps */ /* Functions used for hash maps */
int my_str_hash_fn(void *key); unsigned int my_str_hash_fn(const void *key);
bool my_str_equal_fn(void *a, void *b); bool my_str_equal_fn(const void *a, const void *b);
void my_str_free_fn(void *value); void my_str_free_fn(void *value);
int my_int_hash_fn(void *key); unsigned int my_int_hash_fn(const void *key);
bool my_int_equal_fn(void *a, void *b); bool my_int_equal_fn(const void *a, const void *b);
void my_int_free_fn(void *value); void my_int_free_fn(void *value);
#endif #endif

View File

@@ -42,7 +42,7 @@ cws_http *cws_http_parse(char *request_str, int sockfd, cws_config *config) {
/* Not implemented */ /* Not implemented */
cws_http_free(request); cws_http_free(request);
free(request_str_cpy); free(request_str_cpy);
cws_http_send_error_page(request, CWS_HTTP_NOT_IMPLEMENTED, "501 Not Implemented", "501 Not Implemented"); cws_http_send_error_page(request, CWS_HTTP_NOT_IMPLEMENTED, "501 Not Implemented", "501 Not Implemented");
} }
@@ -77,7 +77,7 @@ cws_http *cws_http_parse(char *request_str, int sockfd, cws_config *config) {
strncpy(request->http_version, pch, CWS_HTTP_VERSION_LEN); strncpy(request->http_version, pch, CWS_HTTP_VERSION_LEN);
/* Parse headers until a \r\n */ /* Parse headers until a \r\n */
request->headers = cws_hm_init(my_str_hash_fn, my_str_equal_fn, my_str_free_fn, my_str_free_fn); request->headers = mcl_hm_init(my_str_hash_fn, my_str_equal_fn, my_str_free_fn, my_str_free_fn);
char *header_colon; char *header_colon;
while (pch) { while (pch) {
/* Get header line */ /* Get header line */
@@ -100,7 +100,7 @@ cws_http *cws_http_parse(char *request_str, int sockfd, cws_config *config) {
char *hvalue = header_colon + 2; char *hvalue = header_colon + 2;
char *hvalue_dup = strdup(hvalue); char *hvalue_dup = strdup(hvalue);
cws_hm_set(request->headers, hkey_dup, hvalue_dup); mcl_hm_set(request->headers, hkey_dup, hvalue_dup);
} }
/* TODO: Parse body */ /* TODO: Parse body */
@@ -276,6 +276,6 @@ void cws_http_send_error_page(cws_http *request, cws_http_status status, char *t
} }
void cws_http_free(cws_http *request) { void cws_http_free(cws_http *request) {
cws_hm_free(request->headers); mcl_hm_free(request->headers);
free(request); free(request);
} }

View File

@@ -19,6 +19,21 @@
volatile sig_atomic_t cws_server_run = 1; volatile sig_atomic_t cws_server_run = 1;
void cws_server_setup_hints(struct addrinfo *hints, size_t len, const char *hostname) {
memset(hints, 0, len);
/* IPv4 or IPv6 */
hints->ai_family = AF_UNSPEC;
/* TCP */
hints->ai_socktype = SOCK_STREAM;
if (hostname == NULL) {
/* Fill in IP for me */
hints->ai_flags = AI_PASSIVE;
}
}
int cws_server_start(cws_config *config) { int cws_server_start(cws_config *config) {
struct addrinfo hints; struct addrinfo hints;
struct addrinfo *res; struct addrinfo *res;
@@ -52,11 +67,12 @@ int cws_server_start(cws_config *config) {
status = listen(sockfd, CWS_SERVER_BACKLOG); status = listen(sockfd, CWS_SERVER_BACKLOG);
if (status != 0) { if (status != 0) {
CWS_LOG_ERROR("listen(): %s", strerror(status)); CWS_LOG_ERROR("listen(): %s", strerror(errno));
return -1; return -1;
} }
cws_server_loop(sockfd, config); int ret = cws_server_loop(sockfd, config);
CWS_LOG_DEBUG("cws_server_loop ret: %d", ret);
freeaddrinfo(res); freeaddrinfo(res);
close(sockfd); close(sockfd);
@@ -64,32 +80,42 @@ int cws_server_start(cws_config *config) {
return 0; return 0;
} }
void cws_server_setup_hints(struct addrinfo *hints, size_t len, const char *hostname) { int cws_server_loop(int sockfd, cws_config *config) {
memset(hints, 0, len);
/* IPv4 or IPv6 */
hints->ai_family = AF_UNSPEC;
/* TCP */
hints->ai_socktype = SOCK_STREAM;
if (hostname == NULL) {
/* Fill in IP for me */
hints->ai_flags = AI_PASSIVE;
}
}
void cws_server_loop(int sockfd, cws_config *config) {
struct sockaddr_storage their_sa; struct sockaddr_storage their_sa;
socklen_t theirsa_size = sizeof their_sa; socklen_t theirsa_size = sizeof their_sa;
int ret;
cws_hashmap *clients = cws_hm_init(my_int_hash_fn, my_int_equal_fn, NULL, my_int_free_fn); mcl_hashmap *clients = mcl_hm_init(my_int_hash_fn, my_int_equal_fn, NULL, my_int_free_fn);
if (!clients) {
return -1;
}
int epfd = epoll_create1(0); int epfd = epoll_create1(0);
cws_fd_set_nonblocking(sockfd);
cws_epoll_add(epfd, sockfd, EPOLLIN | EPOLLET);
struct epoll_event *revents = malloc(CWS_SERVER_EPOLL_MAXEVENTS * sizeof(struct epoll_event)); ret = cws_fd_set_nonblocking(sockfd);
if (ret < 0) {
mcl_hm_free(clients);
close(epfd);
return -1;
}
ret = cws_epoll_add(epfd, sockfd, EPOLLIN | EPOLLET);
if (ret < 0) {
mcl_hm_free(clients);
close(epfd);
return -1;
}
struct epoll_event *revents = (struct epoll_event *)malloc(CWS_SERVER_EPOLL_MAXEVENTS * sizeof(struct epoll_event));
if (!revents) {
mcl_hm_free(clients);
close(epfd);
return -1;
}
int client_fd; int client_fd;
while (cws_server_run) { while (cws_server_run) {
@@ -99,13 +125,18 @@ void cws_server_loop(int sockfd, cws_config *config) {
if (revents[i].data.fd == sockfd) { if (revents[i].data.fd == sockfd) {
/* New client */ /* New client */
char ip[INET_ADDRSTRLEN]; char ip[INET_ADDRSTRLEN];
client_fd = cws_server_accept_client(sockfd, &their_sa, &theirsa_size); client_fd = cws_server_accept_client(sockfd, &their_sa, &theirsa_size);
if (client_fd < 0) {
continue;
}
cws_utils_get_client_ip(&their_sa, ip); cws_utils_get_client_ip(&their_sa, ip);
CWS_LOG_INFO("Client (%s) connected", ip); CWS_LOG_INFO("Client (%s) connected", ip);
cws_fd_set_nonblocking(client_fd); cws_fd_set_nonblocking(client_fd);
cws_epoll_add(epfd, client_fd, EPOLLIN); cws_epoll_add(epfd, client_fd, EPOLLIN);
cws_hm_set(clients, &client_fd, &their_sa); mcl_hm_set(clients, &client_fd, &their_sa);
} else { } else {
char data[4096] = {0}; char data[4096] = {0};
char ip[INET_ADDRSTRLEN] = {0}; char ip[INET_ADDRSTRLEN] = {0};
@@ -115,7 +146,7 @@ void cws_server_loop(int sockfd, cws_config *config) {
const ssize_t bytes_read = recv(client_fd, data, sizeof data, 0); const ssize_t bytes_read = recv(client_fd, data, sizeof data, 0);
/* Retrieve client ip */ /* Retrieve client ip */
cws_bucket *client = cws_hm_get(clients, &client_fd); mcl_bucket *client = mcl_hm_get(clients, &client_fd);
struct sockaddr_storage client_sas = *(struct sockaddr_storage *)client->value; struct sockaddr_storage client_sas = *(struct sockaddr_storage *)client->value;
cws_utils_get_client_ip(&client_sas, ip); cws_utils_get_client_ip(&client_sas, ip);
@@ -125,7 +156,7 @@ void cws_server_loop(int sockfd, cws_config *config) {
cws_server_close_client(epfd, client_fd, clients); cws_server_close_client(epfd, client_fd, clients);
continue; continue;
} }
if (bytes_read < 0) { if (bytes_read < 0) {
if (errno != EAGAIN && errno != EWOULDBLOCK) { if (errno != EAGAIN && errno != EWOULDBLOCK) {
/* Error during read, handle it (close client) */ /* Error during read, handle it (close client) */
@@ -157,11 +188,13 @@ void cws_server_loop(int sockfd, cws_config *config) {
/* Clean up everything */ /* Clean up everything */
free(revents); free(revents);
close(epfd); close(epfd);
cws_hm_free(clients); mcl_hm_free(clients);
CWS_LOG_INFO("Closing..."); CWS_LOG_INFO("Closing...");
return 0;
} }
void cws_epoll_add(int epfd, int sockfd, uint32_t events) { int cws_epoll_add(int epfd, int sockfd, uint32_t events) {
struct epoll_event event; struct epoll_event event;
event.events = events; event.events = events;
event.data.fd = sockfd; event.data.fd = sockfd;
@@ -169,26 +202,32 @@ void cws_epoll_add(int epfd, int sockfd, uint32_t events) {
if (status != 0) { if (status != 0) {
CWS_LOG_ERROR("epoll_ctl_add(): %s", strerror(errno)); CWS_LOG_ERROR("epoll_ctl_add(): %s", strerror(errno));
exit(EXIT_FAILURE); return -1;
} }
return 0;
} }
void cws_epoll_del(int epfd, int sockfd) { int cws_epoll_del(int epfd, int sockfd) {
const int status = epoll_ctl(epfd, EPOLL_CTL_DEL, sockfd, NULL); const int status = epoll_ctl(epfd, EPOLL_CTL_DEL, sockfd, NULL);
if (status != 0) { if (status != 0) {
CWS_LOG_ERROR("epoll_ctl_del(): %s", strerror(errno)); CWS_LOG_ERROR("epoll_ctl_del(): %s", strerror(errno));
exit(EXIT_FAILURE); return -1;
} }
return 0;
} }
void cws_fd_set_nonblocking(int sockfd) { int cws_fd_set_nonblocking(int sockfd) {
const int status = fcntl(sockfd, F_SETFL, O_NONBLOCK); const int status = fcntl(sockfd, F_SETFL, O_NONBLOCK);
if (status == -1) { if (status == -1) {
CWS_LOG_ERROR("fcntl(): %s", strerror(errno)); CWS_LOG_ERROR("fcntl(): %s", strerror(errno));
exit(EXIT_FAILURE); return -1;
} }
return 0;
} }
int cws_server_accept_client(int sockfd, struct sockaddr_storage *their_sa, socklen_t *theirsa_size) { int cws_server_accept_client(int sockfd, struct sockaddr_storage *their_sa, socklen_t *theirsa_size) {
@@ -204,42 +243,7 @@ int cws_server_accept_client(int sockfd, struct sockaddr_storage *their_sa, sock
return client_fd; return client_fd;
} }
void cws_server_close_client(int epfd, int client_fd, cws_hashmap *hashmap) { void cws_server_close_client(int epfd, int client_fd, mcl_hashmap *hashmap) {
cws_epoll_del(epfd, client_fd); cws_epoll_del(epfd, client_fd);
cws_hm_remove(hashmap, &client_fd); mcl_hm_remove(hashmap, &client_fd);
}
SSL_CTX *cws_ssl_create_context() {
const SSL_METHOD *method;
SSL_CTX *ctx;
method = TLS_server_method();
ctx = SSL_CTX_new(method);
if (!ctx) {
CWS_LOG_ERROR("SSL_CTX_new()");
return NULL;
}
return ctx;
}
bool cws_ssl_configure(SSL_CTX *context, cws_config *config) {
int ret;
ret = SSL_CTX_use_certificate_file(context, config->cert, SSL_FILETYPE_PEM);
if (ret <= 0) {
CWS_LOG_ERROR("SSL_CTX_use_certificate_file()");
return false;
}
ret = SSL_CTX_use_PrivateKey_file(context, config->key, SSL_FILETYPE_PEM);
if (ret <= 0) {
CWS_LOG_ERROR("SSL_CTX_use_PrivateKey_file()");
return false;
}
return true;
} }

View File

@@ -4,32 +4,36 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
cws_hashmap *cws_hm_init(cws_hash_fn *hash_fn, cws_equal_fn *equal_fn, cws_free_key_fn *free_key_fn, cws_free_value_fn *free_value_fn) { mcl_hashmap *mcl_hm_init(mcl_hash_fn *hash_fn, mcl_equal_fn *equal_fn, mcl_free_key_fn *free_key_fn, mcl_free_value_fn *free_value_fn) {
/* Allocate hash map struct */ /* Allocate memory for hash map struct */
cws_hashmap *hashmap = (cws_hashmap *)malloc(sizeof(cws_hashmap)); mcl_hashmap *hashmap = malloc(sizeof(mcl_hashmap));
if (hashmap == NULL) { if (hashmap == NULL) {
return NULL; return NULL;
} }
/* Populate hash map with given parameters */ /* Initialize hash map with given parameters */
hashmap->hash_fn = hash_fn; hashmap->hash_fn = hash_fn;
hashmap->equal_fn = equal_fn; hashmap->equal_fn = equal_fn;
hashmap->free_key_fn = free_key_fn; hashmap->free_key_fn = free_key_fn;
hashmap->free_value_fn = free_value_fn; hashmap->free_value_fn = free_value_fn;
/* Clear cws_bucket map */
/* Clear all buckets in the map */
memset(hashmap->map, 0, sizeof(hashmap->map)); memset(hashmap->map, 0, sizeof(hashmap->map));
return hashmap; return hashmap;
} }
void cws_hm_free(cws_hashmap *hashmap) { void mcl_hm_free(mcl_hashmap *hashmap) {
if (hashmap == NULL) { if (hashmap == NULL) {
return; return;
} }
for (size_t i = 0; i < CWS_HASHMAP_SIZE; ++i) { /* Iterate through all buckets in the hash map */
cws_bucket *bucket = &hashmap->map[i]; for (size_t i = 0; i < MYCLIB_HASHMAP_SIZE; ++i) {
mcl_bucket *bucket = &hashmap->map[i];
/* Free the first bucket if it contains data */
if (bucket->key != NULL) { if (bucket->key != NULL) {
if (hashmap->free_key_fn != NULL) { if (hashmap->free_key_fn != NULL) {
hashmap->free_key_fn(bucket->key); hashmap->free_key_fn(bucket->key);
@@ -39,99 +43,101 @@ void cws_hm_free(cws_hashmap *hashmap) {
} }
} }
/* Free all chained buckets */
bucket = bucket->next; bucket = bucket->next;
while (bucket) { while (bucket != NULL) {
if (hashmap->free_key_fn != NULL) { if (hashmap->free_key_fn != NULL) {
hashmap->free_key_fn(bucket->key); hashmap->free_key_fn(bucket->key);
} }
if (hashmap->free_value_fn != NULL) { if (hashmap->free_value_fn != NULL) {
hashmap->free_value_fn(bucket->value); hashmap->free_value_fn(bucket->value);
} }
cws_bucket *next = bucket->next; mcl_bucket *next = bucket->next;
free(bucket); free(bucket);
bucket = next; bucket = next;
} }
} }
/* Free the hash map structure itself */
free(hashmap); free(hashmap);
} }
bool cws_hm_set(cws_hashmap *hashmap, void *key, void *value) { bool mcl_hm_set(mcl_hashmap *hashmap, void *key, void *value) {
if (hashmap == NULL || key == NULL || value == NULL) { /* Validate input parameters */
if (hashmap == NULL || key == NULL) {
return false; return false;
} }
/* Get hash index */ /* Calculate hash index for the key */
int index = hashmap->hash_fn(key) % CWS_HASHMAP_SIZE; int index = hashmap->hash_fn(key) % MYCLIB_HASHMAP_SIZE;
cws_bucket *bucket = &hashmap->map[index]; mcl_bucket *bucket = &hashmap->map[index];
/* Check if the key at index is empty */ /* If bucket is empty, insert new key-value pair */
if (bucket->key == NULL) { if (bucket->key == NULL) {
/* Bucket is empty */
/* Set the key and value */
bucket->key = key; bucket->key = key;
bucket->value = value; bucket->value = value;
bucket->next = NULL; bucket->next = NULL;
return true; return true;
} }
/* Check if bucket is already set */ /* Check if first bucket has the same key */
if (hashmap->equal_fn(bucket->key, key)) { if (hashmap->equal_fn(bucket->key, key)) {
/* Same key, free value and update it */ /* Update existing value, free old value if needed */
if (hashmap->free_value_fn != NULL) { if (hashmap->free_value_fn != NULL && bucket->value != NULL) {
hashmap->free_value_fn(bucket->value); hashmap->free_value_fn(bucket->value);
} }
bucket->value = value; bucket->value = value;
return true; return true;
} }
/* Key not found, iterate through the linked list */ /* Search through the collision chain */
cws_bucket *next = bucket->next; mcl_bucket *current = bucket->next;
while (next) { while (current != NULL) {
if (hashmap->equal_fn(next->key, key)) { if (hashmap->equal_fn(current->key, key)) {
/* Same key, free value and update it */ /* Update existing value, free old value if needed */
if (hashmap->free_value_fn != NULL) { if (hashmap->free_value_fn != NULL && current->value != NULL) {
hashmap->free_value_fn(next->value); hashmap->free_value_fn(current->value);
} }
next->value = value; current->value = value;
return true; return true;
} }
next = next->next; current = current->next;
} }
/* Append the new key/value to the head of the linked list */ /* Key not found, create new bucket and add to chain */
next = (cws_bucket *)malloc(sizeof(cws_bucket)); mcl_bucket *new_bucket = malloc(sizeof(mcl_bucket));
if (next == NULL) { if (new_bucket == NULL) {
return false; return false; /* Memory allocation failed */
} }
next->key = key;
next->value = value; /* Initialize new bucket and insert at head of chain */
next->next = bucket->next; new_bucket->key = key;
bucket->next = next; new_bucket->value = value;
new_bucket->next = bucket->next;
bucket->next = new_bucket;
return true; return true;
} }
cws_bucket *cws_hm_get(cws_hashmap *hashmap, void *key) { mcl_bucket *mcl_hm_get(mcl_hashmap *hashmap, void *key) {
/* Return if hash map or key is null */ /* Validate input parameters */
if (hashmap == NULL || key == NULL) { if (hashmap == NULL || key == NULL) {
return NULL; return NULL;
} }
int index = hashmap->hash_fn(key) % CWS_HASHMAP_SIZE; /* Calculate hash index for the key */
cws_bucket *bucket = &hashmap->map[index]; int index = hashmap->hash_fn(key) % MYCLIB_HASHMAP_SIZE;
mcl_bucket *bucket = &hashmap->map[index];
/* Key is not in the hash map */ /* Return NULL if bucket is empty */
if (bucket->key == NULL) { if (bucket->key == NULL) {
return NULL; return NULL;
} }
/* Iterate through the linked list */ /* Search through the collision chain */
while (bucket) { while (bucket != NULL) {
if (hashmap->equal_fn(bucket->key, key)) { if (hashmap->equal_fn(bucket->key, key)) {
return bucket; return bucket; /* Key found */
} }
bucket = bucket->next; bucket = bucket->next;
} }
@@ -140,55 +146,70 @@ cws_bucket *cws_hm_get(cws_hashmap *hashmap, void *key) {
return NULL; return NULL;
} }
bool cws_hm_remove(cws_hashmap *hashmap, void *key) { static void mcl_free_bucket_content(mcl_hashmap *hashmap, mcl_bucket *bucket) {
/* Free key if free function is provided */
if (hashmap->free_key_fn != NULL && bucket->key != NULL) {
hashmap->free_key_fn(bucket->key);
}
/* Free value if free function is provided */
if (hashmap->free_value_fn != NULL && bucket->value != NULL) {
hashmap->free_value_fn(bucket->value);
}
}
bool mcl_hm_remove(mcl_hashmap *hashmap, void *key) {
/* Validate input parameters */
if (hashmap == NULL || key == NULL) { if (hashmap == NULL || key == NULL) {
return false; return false;
} }
int index = hashmap->hash_fn(key) % CWS_HASHMAP_SIZE; /* Calculate hash index for the key */
cws_bucket *bucket = &hashmap->map[index]; int index = hashmap->hash_fn(key) % MYCLIB_HASHMAP_SIZE;
mcl_bucket *bucket = &hashmap->map[index];
/* Return false if bucket is empty */
if (bucket->key == NULL) { if (bucket->key == NULL) {
return false; return false;
} }
/* Check if first bucket contains the key to remove */
if (hashmap->equal_fn(bucket->key, key)) { if (hashmap->equal_fn(bucket->key, key)) {
if (hashmap->free_key_fn != NULL) { /* Free the content of the bucket */
hashmap->free_key_fn(bucket->key); mcl_free_bucket_content(hashmap, bucket);
}
if (hashmap->free_value_fn != NULL) {
hashmap->free_value_fn(bucket->value);
}
if (bucket->next != NULL) { if (bucket->next != NULL) {
bucket->key = bucket->next->key; /* Move next bucket's content to first bucket and free the next bucket */
bucket->value = bucket->next->value; mcl_bucket *to_free = bucket->next;
bucket->next = bucket->next->next; bucket->key = to_free->key;
bucket->value = to_free->value;
bucket->next = to_free->next;
free(to_free);
} else { } else {
/* No next bucket, mark first bucket as empty */
bucket->key = NULL; bucket->key = NULL;
bucket->value = NULL;
bucket->next = NULL;
} }
return true; return true;
} }
cws_bucket *next = bucket->next; /* Search through the collision chain */
mcl_bucket *prev = bucket;
while (next) { mcl_bucket *current = bucket->next;
if (hashmap->equal_fn(next->key, key)) {
if (hashmap->free_key_fn != NULL) {
hashmap->free_key_fn(next->key);
}
if (hashmap->free_value_fn != NULL) {
hashmap->free_value_fn(next->value);
}
bucket->next = next->next;
free(next);
while (current != NULL) {
if (hashmap->equal_fn(current->key, key)) {
/* Key found, free content and unlink bucket */
mcl_free_bucket_content(hashmap, current);
prev->next = current->next;
free(current);
return true; return true;
} }
bucket = next; prev = current;
next = next->next; current = current->next;
} }
/* Key not found */
return false; return false;
} }

View File

@@ -61,7 +61,7 @@ char *cws_strip(char *str) {
return str; return str;
} }
int my_str_hash_fn(void *key) { unsigned int my_str_hash_fn(const void *key) {
char *key_str = (char *)key; char *key_str = (char *)key;
size_t key_len = strlen(key_str); size_t key_len = strlen(key_str);
@@ -74,7 +74,7 @@ int my_str_hash_fn(void *key) {
return total % 2069; return total % 2069;
} }
bool my_str_equal_fn(void *a, void *b) { bool my_str_equal_fn(const void *a, const void *b) {
if (strcmp((char *)a, (char *)b) == 0) { if (strcmp((char *)a, (char *)b) == 0) {
return true; return true;
} }
@@ -84,9 +84,9 @@ bool my_str_equal_fn(void *a, void *b) {
void my_str_free_fn(void *value) { free(value); } void my_str_free_fn(void *value) { free(value); }
int my_int_hash_fn(void *key) { return *(int *)key; } unsigned int my_int_hash_fn(const void *key) { return *(int *)key; }
bool my_int_equal_fn(void *a, void *b) { bool my_int_equal_fn(const void *a, const void *b) {
int ai = *(int *)a; int ai = *(int *)a;
int bi = *(int *)b; int bi = *(int *)b;