diff --git a/include/http/http.h b/include/http/http.h index a783b35..13daaf3 100644 --- a/include/http/http.h +++ b/include/http/http.h @@ -34,7 +34,7 @@ typedef struct cws_http_t { char location[CWS_HTTP_LOCATION_LEN]; /**< Resource requested */ char location_path[CWS_HTTP_LOCATION_PATH_LEN]; /**< Full resource path */ char http_version[CWS_HTTP_VERSION_LEN]; /**< HTTP version */ - cws_hashmap *headers; /**< Headers hash map */ + mcl_hashmap *headers; /**< Headers hash map */ } cws_http; /* Connection */ /* Accept-Encoding */ diff --git a/include/server/server.h b/include/server/server.h index 9a4d63a..58acd54 100644 --- a/include/server/server.h +++ b/include/server/server.h @@ -22,14 +22,6 @@ /* Main server loop */ 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 * @@ -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); +/** + * @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 * * @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 @@ -53,7 +53,7 @@ void cws_server_loop(int sockfd, cws_config *config); * @param[in] sockfd The file descriptor to watch * @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 @@ -61,14 +61,14 @@ void cws_epoll_add(int epfd, int sockfd, uint32_t events); * @param[in] epfd epoll file descriptor * @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 * * @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 @@ -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] hashmap Clients hash map */ -void cws_server_close_client(int epfd, int client_fd, cws_hashmap *hashmap); - -/* Undocumented functions */ -SSL_CTX *cws_ssl_create_context(); -bool cws_ssl_configure(SSL_CTX *context, cws_config *config); +void cws_server_close_client(int epfd, int client_fd, mcl_hashmap *hashmap); #endif diff --git a/include/utils/hashmap.h b/include/utils/hashmap.h index a7ef13b..9b4e96d 100644 --- a/include/utils/hashmap.h +++ b/include/utils/hashmap.h @@ -1,26 +1,30 @@ -#ifndef CWS_HASHMAP_H -#define CWS_HASHMAP_H +#ifndef MYCLIB_HASHMAP_H +#define MYCLIB_HASHMAP_H #include +#include -#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 *value; /**< Pointer to the value */ - struct cws_bucket_t *next; /**< Pointer to the next bucket in case of collision */ -} cws_bucket; + struct mcl_bucket_t *next; /**< Pointer to the next bucket in case of collision */ +} mcl_bucket; /** * @brief Function pointer type for a hash function * * @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 @@ -29,78 +33,95 @@ typedef int cws_hash_fn(void *key); * @param[in] key_b Pointer to the second key * @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 * * @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 * * @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 - */ -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 - * @param[in] equal_fn Function used to compare keys - * @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 + * Contains function pointers for hash computation, key comparison, + * and memory management, along with the bucket array. */ -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 */ -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] key Pointer to the key to insert - * @param[in] value Pointer to the value to insert - * @return true if the operation succeeded, false otherwise + * @param[in] key Pointer to the key to insert (must not be NULL) + * @param[in] value Pointer to the value to insert (can be NULL) + * @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] 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] key Pointer to the key to remove, this pointer will be freed so pay attention - * @return False if the key is not found, otherwise true + * @param[in] key Pointer to the key to remove + * @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 */ diff --git a/include/utils/utils.h b/include/utils/utils.h index 1481519..f533420 100644 --- a/include/utils/utils.h +++ b/include/utils/utils.h @@ -33,12 +33,12 @@ void cws_utils_get_client_ip(struct sockaddr_storage *sa, char *ip); char *cws_strip(char *str); /* Functions used for hash maps */ -int my_str_hash_fn(void *key); -bool my_str_equal_fn(void *a, void *b); +unsigned int my_str_hash_fn(const void *key); +bool my_str_equal_fn(const void *a, const void *b); void my_str_free_fn(void *value); -int my_int_hash_fn(void *key); -bool my_int_equal_fn(void *a, void *b); +unsigned int my_int_hash_fn(const void *key); +bool my_int_equal_fn(const void *a, const void *b); void my_int_free_fn(void *value); #endif diff --git a/src/http/http.c b/src/http/http.c index 435d579..d8e9584 100644 --- a/src/http/http.c +++ b/src/http/http.c @@ -42,7 +42,7 @@ cws_http *cws_http_parse(char *request_str, int sockfd, cws_config *config) { /* Not implemented */ cws_http_free(request); free(request_str_cpy); - + 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); /* 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; while (pch) { /* 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_dup = strdup(hvalue); - cws_hm_set(request->headers, hkey_dup, hvalue_dup); + mcl_hm_set(request->headers, hkey_dup, hvalue_dup); } /* 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) { - cws_hm_free(request->headers); + mcl_hm_free(request->headers); free(request); } diff --git a/src/server/server.c b/src/server/server.c index eace65f..54d1e8f 100644 --- a/src/server/server.c +++ b/src/server/server.c @@ -19,6 +19,21 @@ 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) { struct addrinfo hints; struct addrinfo *res; @@ -52,11 +67,12 @@ int cws_server_start(cws_config *config) { status = listen(sockfd, CWS_SERVER_BACKLOG); if (status != 0) { - CWS_LOG_ERROR("listen(): %s", strerror(status)); + CWS_LOG_ERROR("listen(): %s", strerror(errno)); 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); close(sockfd); @@ -64,32 +80,42 @@ int cws_server_start(cws_config *config) { return 0; } -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; - } -} - -void cws_server_loop(int sockfd, cws_config *config) { +int cws_server_loop(int sockfd, cws_config *config) { struct sockaddr_storage 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); - 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; while (cws_server_run) { @@ -99,13 +125,18 @@ void cws_server_loop(int sockfd, cws_config *config) { if (revents[i].data.fd == sockfd) { /* New client */ char ip[INET_ADDRSTRLEN]; + 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_LOG_INFO("Client (%s) connected", ip); cws_fd_set_nonblocking(client_fd); cws_epoll_add(epfd, client_fd, EPOLLIN); - cws_hm_set(clients, &client_fd, &their_sa); + mcl_hm_set(clients, &client_fd, &their_sa); } else { char data[4096] = {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); /* 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; 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); continue; } - + if (bytes_read < 0) { if (errno != EAGAIN && errno != EWOULDBLOCK) { /* Error during read, handle it (close client) */ @@ -157,11 +188,13 @@ void cws_server_loop(int sockfd, cws_config *config) { /* Clean up everything */ free(revents); close(epfd); - cws_hm_free(clients); + mcl_hm_free(clients); 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; event.events = events; event.data.fd = sockfd; @@ -169,26 +202,32 @@ void cws_epoll_add(int epfd, int sockfd, uint32_t events) { if (status != 0) { 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); if (status != 0) { 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); if (status == -1) { 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) { @@ -204,42 +243,7 @@ int cws_server_accept_client(int sockfd, struct sockaddr_storage *their_sa, sock 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_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; + mcl_hm_remove(hashmap, &client_fd); } diff --git a/src/utils/hashmap.c b/src/utils/hashmap.c index 9008cc2..8bde341 100644 --- a/src/utils/hashmap.c +++ b/src/utils/hashmap.c @@ -4,32 +4,36 @@ #include #include -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) { - /* Allocate hash map struct */ - cws_hashmap *hashmap = (cws_hashmap *)malloc(sizeof(cws_hashmap)); +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 memory for hash map struct */ + mcl_hashmap *hashmap = malloc(sizeof(mcl_hashmap)); if (hashmap == NULL) { return NULL; } - /* Populate hash map with given parameters */ + /* Initialize hash map with given parameters */ hashmap->hash_fn = hash_fn; hashmap->equal_fn = equal_fn; hashmap->free_key_fn = free_key_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)); return hashmap; } -void cws_hm_free(cws_hashmap *hashmap) { +void mcl_hm_free(mcl_hashmap *hashmap) { if (hashmap == NULL) { return; } - for (size_t i = 0; i < CWS_HASHMAP_SIZE; ++i) { - cws_bucket *bucket = &hashmap->map[i]; + /* Iterate through all buckets in the hash map */ + 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 (hashmap->free_key_fn != NULL) { hashmap->free_key_fn(bucket->key); @@ -39,99 +43,101 @@ void cws_hm_free(cws_hashmap *hashmap) { } } + /* Free all chained buckets */ bucket = bucket->next; - while (bucket) { + while (bucket != NULL) { if (hashmap->free_key_fn != NULL) { hashmap->free_key_fn(bucket->key); } if (hashmap->free_value_fn != NULL) { hashmap->free_value_fn(bucket->value); } - cws_bucket *next = bucket->next; + mcl_bucket *next = bucket->next; free(bucket); bucket = next; } } + /* Free the hash map structure itself */ free(hashmap); } -bool cws_hm_set(cws_hashmap *hashmap, void *key, void *value) { - if (hashmap == NULL || key == NULL || value == NULL) { +bool mcl_hm_set(mcl_hashmap *hashmap, void *key, void *value) { + /* Validate input parameters */ + if (hashmap == NULL || key == NULL) { return false; } - /* Get hash index */ - int index = hashmap->hash_fn(key) % CWS_HASHMAP_SIZE; - cws_bucket *bucket = &hashmap->map[index]; + /* Calculate hash index for the key */ + int index = hashmap->hash_fn(key) % MYCLIB_HASHMAP_SIZE; + 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) { - /* Bucket is empty */ - /* Set the key and value */ bucket->key = key; bucket->value = value; bucket->next = NULL; - return true; } - /* Check if bucket is already set */ + /* Check if first bucket has the same key */ if (hashmap->equal_fn(bucket->key, key)) { - /* Same key, free value and update it */ - if (hashmap->free_value_fn != NULL) { + /* Update existing value, free old value if needed */ + if (hashmap->free_value_fn != NULL && bucket->value != NULL) { hashmap->free_value_fn(bucket->value); } bucket->value = value; - return true; } - /* Key not found, iterate through the linked list */ - cws_bucket *next = bucket->next; - while (next) { - if (hashmap->equal_fn(next->key, key)) { - /* Same key, free value and update it */ - if (hashmap->free_value_fn != NULL) { - hashmap->free_value_fn(next->value); + /* Search through the collision chain */ + mcl_bucket *current = bucket->next; + while (current != NULL) { + if (hashmap->equal_fn(current->key, key)) { + /* Update existing value, free old value if needed */ + if (hashmap->free_value_fn != NULL && current->value != NULL) { + hashmap->free_value_fn(current->value); } - next->value = value; + current->value = value; return true; } - next = next->next; + current = current->next; } - /* Append the new key/value to the head of the linked list */ - next = (cws_bucket *)malloc(sizeof(cws_bucket)); - if (next == NULL) { - return false; + /* Key not found, create new bucket and add to chain */ + mcl_bucket *new_bucket = malloc(sizeof(mcl_bucket)); + if (new_bucket == NULL) { + return false; /* Memory allocation failed */ } - next->key = key; - next->value = value; - next->next = bucket->next; - bucket->next = next; + + /* Initialize new bucket and insert at head of chain */ + new_bucket->key = key; + new_bucket->value = value; + new_bucket->next = bucket->next; + bucket->next = new_bucket; return true; } -cws_bucket *cws_hm_get(cws_hashmap *hashmap, void *key) { - /* Return if hash map or key is null */ +mcl_bucket *mcl_hm_get(mcl_hashmap *hashmap, void *key) { + /* Validate input parameters */ if (hashmap == NULL || key == NULL) { return NULL; } - int index = hashmap->hash_fn(key) % CWS_HASHMAP_SIZE; - cws_bucket *bucket = &hashmap->map[index]; + /* Calculate hash index for the key */ + 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) { return NULL; } - /* Iterate through the linked list */ - while (bucket) { + /* Search through the collision chain */ + while (bucket != NULL) { if (hashmap->equal_fn(bucket->key, key)) { - return bucket; + return bucket; /* Key found */ } bucket = bucket->next; } @@ -140,55 +146,70 @@ cws_bucket *cws_hm_get(cws_hashmap *hashmap, void *key) { 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) { return false; } - int index = hashmap->hash_fn(key) % CWS_HASHMAP_SIZE; - cws_bucket *bucket = &hashmap->map[index]; + /* Calculate hash index for the key */ + 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) { return false; } + /* Check if first bucket contains the key to remove */ if (hashmap->equal_fn(bucket->key, key)) { - if (hashmap->free_key_fn != NULL) { - hashmap->free_key_fn(bucket->key); - } - if (hashmap->free_value_fn != NULL) { - hashmap->free_value_fn(bucket->value); - } + /* Free the content of the bucket */ + mcl_free_bucket_content(hashmap, bucket); if (bucket->next != NULL) { - bucket->key = bucket->next->key; - bucket->value = bucket->next->value; - bucket->next = bucket->next->next; + /* Move next bucket's content to first bucket and free the next bucket */ + mcl_bucket *to_free = bucket->next; + bucket->key = to_free->key; + bucket->value = to_free->value; + bucket->next = to_free->next; + free(to_free); } else { + /* No next bucket, mark first bucket as empty */ bucket->key = NULL; + bucket->value = NULL; + bucket->next = NULL; } - return true; } - cws_bucket *next = bucket->next; - - while (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); + /* Search through the collision chain */ + mcl_bucket *prev = bucket; + mcl_bucket *current = bucket->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; } - bucket = next; - next = next->next; + prev = current; + current = current->next; } + /* Key not found */ return false; } diff --git a/src/utils/utils.c b/src/utils/utils.c index 87e8f5d..5266b7d 100644 --- a/src/utils/utils.c +++ b/src/utils/utils.c @@ -61,7 +61,7 @@ char *cws_strip(char *str) { return str; } -int my_str_hash_fn(void *key) { +unsigned int my_str_hash_fn(const void *key) { char *key_str = (char *)key; size_t key_len = strlen(key_str); @@ -74,7 +74,7 @@ int my_str_hash_fn(void *key) { 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) { return true; } @@ -84,9 +84,9 @@ bool my_str_equal_fn(void *a, void *b) { 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 bi = *(int *)b;