comparison th_datastruct.c @ 736:ca837a4417f5

Add simple growing pointerlist data stucture implementation.
author Matti Hamalainen <ccr@tnsp.org>
date Wed, 07 Dec 2022 15:03:09 +0200
parents 31bc1ed07cf5
children 3091fd1987e9
comparison
equal deleted inserted replaced
735:31bc1ed07cf5 736:ca837a4417f5
587 memcpy(*buf + *len, str, slen + 1); 587 memcpy(*buf + *len, str, slen + 1);
588 (*len) += slen; 588 (*len) += slen;
589 589
590 return true; 590 return true;
591 } 591 }
592
593
594 int th_ptrlist_init(th_ptrlist_t *list, const size_t ninitial, const size_t ngrow)
595 {
596 memset(list, 0, sizeof(*list));
597
598 if (ngrow == 0)
599 return THERR_INVALID_ARGS;
600
601 list->nitems = 0;
602 list->nallocated = ninitial;
603 list->ngrow = ngrow;
604
605 if ((list->items = th_malloc(list->nallocated * sizeof(void *))) == NULL)
606 return THERR_MALLOC;
607
608 return THERR_OK;
609 }
610
611
612 int th_ptrlist_new(th_ptrlist_t **list, const size_t ninitial, const size_t ngrow)
613 {
614 int res;
615
616 if ((*list = th_malloc0(sizeof(th_ptrlist_t))) == NULL)
617 return THERR_MALLOC;
618
619 if ((res = th_ptrlist_init(*list, ninitial, ngrow)) != THERR_OK)
620 {
621 th_free(*list);
622 return res;
623 }
624
625 (*list)->is_allocated = true;
626
627 return THERR_OK;
628 }
629
630
631 int th_ptrlist_append(th_ptrlist_t *list, void *str)
632 {
633 if (list->nitems + 1 >= list->nallocated)
634 {
635 list->nallocated += list->ngrow;
636 if ((list->items = th_realloc(list->items, list->nallocated * sizeof(void *))) == NULL)
637 return THERR_MALLOC;
638 }
639
640 list->items[list->nitems++] = str;
641
642 return THERR_OK;
643 }
644
645
646 void th_ptrlist_free(th_ptrlist_t *list, void (*mdeallocator)(void *data))
647 {
648 if (mdeallocator != NULL)
649 {
650 for (size_t i = 0; i < list->nitems; i++)
651 mdeallocator(list->items[i]);
652 }
653
654 th_free(list->items);
655
656 if (list->is_allocated)
657 th_free(list);
658 }