#include #include #include #include #include "message.h" // Defines the node structure struct message_t { char *message; node_id_t received_from, *sent_to; uint16_t message_length, num_sent_to; }; /* API */ message_handle_t message_init(const char *message, uint16_t length, node_id_t received_from) { assert(message && length <= MAX_MESSAGE_LENGTH); message_handle_t message_handle = malloc(sizeof(message_t)); assert(message_handle); message_handle->message = malloc((length + 1) * sizeof(char)); strcpy(message_handle->message, message); message_handle->message_length = length; message_handle->received_from = received_from; message_handle->sent_to = NULL; message_handle->num_sent_to = 0; return message_handle; } void message_free(message_handle_t message_handle) { assert(message_handle); free(message_handle->sent_to); free(message_handle->message); free(message_handle); } void message_add_sent_to(message_handle_t message_handle, node_id_t sent_to) { assert(message_handle); // Expands array by re-allocation space node_id_t *r_sent_to = realloc(message_handle->sent_to, ++(message_handle->num_sent_to) * sizeof(node_id_t)); if (!r_sent_to) { free(r_sent_to); perror("Unable to reallocate memory for message receivers."); exit(EXIT_FAILURE); } message_handle->sent_to = r_sent_to; // ++(message_handle->num_sent_to); message_handle->sent_to[message_handle->num_sent_to - 1] = sent_to; } char *message_get(message_handle_t message_handle, int *length) { assert(message_handle && length); static char *message_buffer = NULL; static int message_buffer_len = 0; if (message_buffer_len != message_handle->message_length + 1) { char *r_message_buffer = (char *) realloc(message_buffer, (message_handle->message_length + 1) * sizeof(char)); if (!r_message_buffer) { free(r_message_buffer); perror("Unable to reallocate memory for message receivers."); exit(EXIT_FAILURE); } message_buffer = r_message_buffer; message_buffer_len = message_handle->message_length + 1; } strcpy(message_buffer, message_handle->message); (*length) = message_handle->message_length; return message_buffer; } bool message_sent_to(message_handle_t message_handle, node_id_t id) { assert(message_handle); for (uint16_t i = 0; i < message_handle->num_sent_to; ++i) { if (message_handle->sent_to[i] == id) { return true; } } return false; }