cscg22-gearboy

CSCG 2022 Challenge 'Gearboy'
git clone https://git.sinitax.com/sinitax/cscg22-gearboy
Log | Files | Refs | sfeed.txt

list.c (1938B)


      1// This is free and unencumbered software released into the public domain.
      2// For more information, please refer to <https://unlicense.org>
      3// bbbbbr 2020
      4
      5#include <stdio.h>
      6#include <string.h>
      7#include <stdlib.h>
      8#include <stdint.h>
      9
     10#include "list.h"
     11
     12#define LIST_GROW_SIZE 50 // grow array by N entries at a time
     13
     14// Initialize the list and it's array
     15// typesize *must* match the type that will be used with the array
     16void list_init(list_type * p_list, size_t array_typesize) {
     17    p_list->typesize = array_typesize;
     18    p_list->count   = 0;
     19    p_list->size    = LIST_GROW_SIZE;
     20    p_list->p_array = (void *)malloc(p_list->size * p_list->typesize);
     21
     22    if (!p_list->p_array) {
     23        printf("BankPack: ERROR: Failed to allocate memory for list!\n");
     24        exit(EXIT_FAILURE);
     25    }
     26}
     27
     28
     29// Free the array memory allocated for the list
     30void list_cleanup(list_type * p_list) {
     31    if (p_list->p_array) {
     32        free (p_list->p_array);
     33        p_list->p_array = NULL;
     34    }
     35}
     36
     37
     38// Add a new item to the lists array, resize if needed
     39// p_newitem *must* be the same type the list was initialized with
     40void list_additem(list_type * p_list, void * p_newitem) {
     41
     42    void * tmp_list;
     43
     44    p_list->count++;
     45
     46    // Grow array if needed
     47    if (p_list->count == p_list->size) {
     48        // Save a copy in case reallocation fails
     49        tmp_list = p_list->p_array;
     50
     51        p_list->size += p_list->typesize * LIST_GROW_SIZE;
     52        p_list->p_array = (void *)realloc(p_list->p_array, p_list->size * p_list->typesize);
     53        // If realloc failed, free original buffer before quitting
     54        if (!p_list->p_array) {
     55            printf("BankPack: ERROR: Failed to reallocate memory for list!\n");
     56            if (tmp_list) free(tmp_list);
     57            exit(EXIT_FAILURE);
     58        }
     59    }
     60
     61    // Copy new entry
     62    memcpy(p_list->p_array + ((p_list->count - 1) * p_list->typesize),
     63           p_newitem,
     64           p_list->typesize);
     65}
     66