From 1678fa286b93baadb030c6c4924eb5b362e4ec3f Mon Sep 17 00:00:00 2001 From: j4nk Date: Thu, 8 Jun 2023 22:07:58 -0400 Subject: [PATCH] Added untested address book --- oct_networking.c | 57 +++++++++++++++++++++++++++++++++++++++++++----- oct_networking.h | 3 ++- 2 files changed, 54 insertions(+), 6 deletions(-) diff --git a/oct_networking.c b/oct_networking.c index 9b2f3a8..a1243cf 100644 --- a/oct_networking.c +++ b/oct_networking.c @@ -24,6 +24,9 @@ struct { int sfd; } oct_network_node; +// Address book currently implemented as a doubly-linked list with O(n) inserts, accesses +// Ideal implementation is hash table with O(1) inserts, accesses +// However, we'll see if this works for now struct { unsigned int size; struct oct_network_ab_entry* first; @@ -198,11 +201,55 @@ void oct_network_ab_init() { int oct_network_ab_insert(char* addr, char* port) { // First create the entry struct oct_network_ab_entry* e = (struct oct_network_ab_entry*)malloc(sizeof(struct oct_network_ab_entry)); - + if (!e) { + OCT_LOG_ERROR("Could not allocate space for address book entry for %s:%s", addr, port); + } + // Then, create the socket - // TODO + if ((e->sfd = oct_network_init_socket(addr, port)) < 0) { + free(e); + return 0; + } + e->next = NULL; + e->prev = oct_network_ab.last; + strncpy(e->addr, addr, NI_MAXHOST); + strncpy(e->port, port, NI_MAXSERV); + if (oct_network_ab.size == 0) { + oct_network_ab.first = e; + } + else { + oct_network_ab.last->next = e; + } + oct_network_ab.last = e; + oct_network_ab.size++; - - - return 0; + return 1; +} + +int oct_network_ab_remove(struct oct_network_ab_entry* e) { + // First, remove node from linked list and fix + if (e == oct_network_ab.first) { + oct_network_ab.first = e->next; + e->next->prev = NULL; + } + else if (e == oct_network_ab.last) { + oct_network_ab.last = e->prev; + e->prev->next = NULL; + } + else { + e->next->prev = e->prev; + e->prev->next = e->next; + } + // Finally, get rid of node + close(e->sfd); + free(e); + oct_network_ab.size--; + + return 1; +} + +void oct_network_ab_deinit() { + while (oct_network_ab.first) { + oct_network_ab_remove(oct_network_ab.first); + } } diff --git a/oct_networking.h b/oct_networking.h index 4f2c836..d21677c 100644 --- a/oct_networking.h +++ b/oct_networking.h @@ -16,6 +16,7 @@ struct oct_network_ab_entry { char addr[NI_MAXHOST]; char port[NI_MAXSERV]; struct oct_network_ab_entry* next; + struct oct_network_ab_entry* prev; }; int oct_network_node_init(char* port, lua_State* L); @@ -31,7 +32,7 @@ int oct_network_send_msg_lua(lua_State* L); void oct_network_ab_init(); int oct_network_ab_insert(char* addr, char* port); int oct_network_ab_remove(struct oct_network_ab_entry* e); -int oct_network_ab_deinit(); +void oct_network_ab_deinit(); #endif