From e9fc779171f0cc5734d0d649eeec1081c354618a Mon Sep 17 00:00:00 2001 From: dam Date: Wed, 31 Aug 2022 16:28:05 +0000 Subject: Removed unused database helper functions. Reworked database to use size_t and ptrdiff_t types to avoid being bound by indexes types constrains. Print task's times. --- misc.c | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) (limited to 'misc.c') diff --git a/misc.c b/misc.c index a192f18..2c734bd 100644 --- a/misc.c +++ b/misc.c @@ -1,4 +1,73 @@ +// Adds task to database. If necessary, expands database capacity. +// Returns success. +bool add_task(database_t* db, const task_t* task) { + assert(db != NULL); + assert(task != NULL); + + if (db->count == UINT32_MAX) { + fprintf(stderr, "Database reached maximum capacity, discarding task '%s'.\n", task->name); + return false; + } + + // If necessary, expand database capacity. + uint32_t current_capacity = db->capacity; + if((db->count + 1) > current_capacity) { + uint32_t new_capacity = current_capacity == 0 ? 2 : + current_capacity >= UINT32_MAX >> 2 ? UINT32_MAX : + current_capacity << 1; + + task_t* new_tasks = realloc(db->tasks, new_capacity * SIZEOF_TASK_T); + if (new_tasks == NULL) { + fprintf(stderr, "Failed to expand database, discarding task '%s'.\n", task->name); + return false; + } + db->capacity = new_capacity; + db->tasks = new_tasks; + } + + // Store new task. + memcpy(&(db->tasks[db->count]), task, SIZEOF_TASK_T); + db->count++; + + return true; +} + +// TODO Remove this task and move code to delete_task. +// Removes task by index from database. If possible, shrinks database capacity. +// Returns success. +bool remove_task(database_t* db, uint32_t index) { + assert(db != NULL); + assert(index < db->count); + + if (index >= db->count) { + fprintf(stderr, "Failed to remove out-of-bounds index '%" PRIu32 "'.", index); + return false; + } + + // Move tasks after the index position to their new positions. + memmove(&db->tasks[index], &db->tasks[index+1], (db->count - index - 1) * SIZEOF_TASK_T); + db->count--; + + // If possible, shrink database capacity. + size_t current_capacity = db->capacity; + if (db->count <= (current_capacity >> 2)) { + ptrdiff_t selected_task_offset = db->tasks - db->active_task; + size_t new_capacity = current_capacity >> 1; + task_t* new_tasks = realloc(db->tasks, new_capacity * SIZEOF_TASK_T); + if (new_tasks == NULL) { + fprintf(stderr, "Failed to shrink database.\n"); + return false; + } + db->capacity = new_capacity; + db->tasks = new_tasks; + db->active_task = db->tasks + selected_task_offset; + // TODO Validate selected_task (may now be above count. + } + + return true; +} + uint32_t CRC32(const uint8_t data[], size_t data_length) { static const uint32_t crc32_table[] = { -- cgit v1.2.3