git.y1.nz

gbdk-2020

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

gbdk-support/romusage/src/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 "logging.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         log_error("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 // New item gets copied, so ok if it's a local var with limited lifetime
     42 void list_additem(list_type * p_list, void * p_newitem) {
     43 
     44     void * tmp_list;
     45 
     46     p_list->count++;
     47 
     48     // Grow array if needed
     49     if (p_list->count == p_list->size) {
     50         // Save a copy in case reallocation fails
     51         tmp_list = p_list->p_array;
     52 
     53         p_list->size += LIST_GROW_SIZE;
     54         p_list->p_array = (void *)realloc(p_list->p_array, p_list->size * p_list->typesize);
     55         // If realloc failed, free original buffer before quitting
     56         if (!p_list->p_array) {
     57             log_error("Error: Failed to reallocate memory for list!\n");
     58             if (tmp_list) {
     59                 free(tmp_list);
     60                 tmp_list = NULL;
     61             }
     62             exit(EXIT_FAILURE);
     63         }
     64     }
     65 
     66     // Copy new entry
     67     memcpy((uint_least8_t *)p_list->p_array + ((p_list->count - 1) * p_list->typesize),
     68            p_newitem,
     69            p_list->typesize);
     70 }
     71 

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