advent2021

Advent of Code 2021 Solutions
git clone git://bsandro.tech/advent2021
Log | Files | Refs | README | LICENSE

util.c (2144B)


      1 #define _DEFAULT_SOURCE
      2 
      3 #include <string.h>
      4 #include <stdlib.h>
      5 #include "util.h"
      6 
      7 void array_init(struct array_t *array, size_t elem_size, size_t cap) {
      8 	assert(array->data == NULL);
      9 	array->cap = cap;
     10 	array->elem_size = elem_size;
     11 	array->data = calloc(cap, elem_size);
     12 	assert(array->data != NULL);
     13 }
     14 
     15 struct array_t array_copy(struct array_t *array) {
     16 	assert(array != NULL);
     17 	assert(array->data != NULL);
     18 	struct array_t ar_copy = { .data = NULL };
     19 	array_init(&ar_copy, array->elem_size, array->count);
     20 	assert(ar_copy.data != NULL);
     21 	memcpy(ar_copy.data, array->data, array->count * array->elem_size);
     22 	ar_copy.count = array->count;
     23 	ar_copy.cap = ar_copy.count;
     24 	ar_copy.elem_size = ar_copy.elem_size;
     25 	return ar_copy;
     26 }
     27 
     28 void array_expand(struct array_t *array) {
     29 	assert(array != NULL);
     30 	size_t new_cap = array->cap * 2;
     31 	array->data = realloc(array->data, array->elem_size * new_cap);
     32 	assert(array->data != NULL);
     33 	array->cap = new_cap;
     34 }
     35 
     36 void array_expand1(struct array_t *array, size_t incr) {
     37 	size_t new_cap = array->cap + incr;
     38 	array->data = realloc(array->data, array->elem_size * new_cap);
     39 	assert(array->data != NULL);
     40 	array->cap = new_cap;
     41 }
     42 
     43 /* ******************* parse plain numbers array *******************/
     44 void parse_numbers_array(struct array_t *numbers, const char *str, const char *delim) {
     45 	assert(numbers != NULL);
     46 	char *tmp = strndup(str, STR_LEN_LIMIT);
     47 	char *token = NULL;
     48 	assert(tmp != NULL);
     49 
     50 	while ((token = strsep(&tmp, delim)) != NULL) {
     51 		int num = atoi(token);
     52 
     53 		if (numbers->count >= numbers->cap) {
     54 			array_expand(numbers);
     55 		}
     56 
     57 		int *data = (int *)numbers->data;
     58 		data[numbers->count++] = num;
     59 	}
     60 
     61 	free(tmp);
     62 }
     63 
     64 //@todo copypasta
     65 void parse_numbers_array_ll(struct array_t *numbers, const char *str, const char *delim) {
     66 	assert(numbers != NULL);
     67 	char *tmp = strndup(str, STR_LEN_LIMIT);
     68 	char *token = NULL;
     69 	assert(tmp != NULL);
     70 
     71 	while ((token = strsep(&tmp, delim)) != NULL) {
     72 		long long num = atoll(token);
     73 
     74 		if (numbers->count >= numbers->cap) {
     75 			array_expand(numbers);
     76 		}
     77 
     78 		long long *data = (long long *)numbers->data;
     79 		data[numbers->count++] = num;
     80 	}
     81 
     82 	free(tmp);
     83 }