git.y1.nz

gbdk-2020

GameBoy Development Kit
download: https://git.y1.nz/archives/gbdk.tar.gz
README | Files | Log | Refs | LICENSE

gbdk-support/makecom/list.c

      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 "common.h"
     11 #include "list.h"
     12 
     13 #define LIST_GROW_SIZE 100 // 50 // grow array by N entries at a time
     14 
     15 // Initialize the list and it's array
     16 // typesize *must* match the type that will be used with the array
     17 void list_init(list_type * p_list, size_t array_typesize) {
     18     p_list->typesize = array_typesize;
     19     p_list->count   = 0;
     20     p_list->size    = LIST_GROW_SIZE;
     21     p_list->p_array = (void *)malloc(p_list->size * p_list->typesize);
     22 
     23     if (!p_list->p_array) {
     24         printf("makecom: ERROR: Failed to allocate memory for list!\n");
     25         exit(EXIT_FAILURE);
     26     }
     27 }
     28 
     29 
     30 // Free the array memory allocated for the list
     31 void list_cleanup(list_type * p_list) {
     32     if (p_list->p_array) {
     33         free (p_list->p_array);
     34         p_list->p_array = NULL;
     35     }
     36 }
     37 
     38 
     39 // Add a new item to the lists array, resize if needed
     40 // p_newitem *must* be the same type the list was initialized with
     41 void list_additem(list_type * p_list, void * p_newitem) {
     42 
     43     void * tmp_list;
     44 
     45     p_list->count++;
     46 
     47     // Grow array if needed
     48     if (p_list->count == p_list->size) {
     49         // Save a copy in case reallocation fails
     50         tmp_list = p_list->p_array;
     51 
     52         p_list->size += LIST_GROW_SIZE;
     53         p_list->p_array = (void *)realloc(p_list->p_array, p_list->size * p_list->typesize);
     54         // If realloc failed, free original buffer before quitting
     55         if (!p_list->p_array) {
     56             printf("makecom: ERROR: Failed to reallocate memory for list!\n");
     57             if (tmp_list) {
     58                 free(tmp_list);
     59                 tmp_list = NULL;
     60             }
     61             exit(EXIT_FAILURE);
     62         }
     63     }
     64 
     65     // Copy new entry
     66     memcpy((uint_least8_t *)p_list->p_array + ((p_list->count - 1) * p_list->typesize),
     67            p_newitem,
     68            p_list->typesize);
     69 }
     70 

This webpage is intended to be an accessible preview of this repository. To get a fuller picture, clone it and use the git CLI.