1 /* dynlist.c: Dynamic lists and buffers in C.
2 * created 1999-Jan-06 15:34 jmk
3 * autodate: 2001-Sep-16 18:08
4 *
5 * by Jim Knoble <jmknoble@pobox.com>
6 * Copyright (C) 1999,2000,2001 Jim Knoble
7 *
8 * Disclaimer:
9 *
10 * The software is provided "as is", without warranty of any kind,
11 * express or implied, including but not limited to the warranties of
12 * merchantability, fitness for a particular purpose and
13 * noninfringement. In no event shall the author(s) be liable for any
14 * claim, damages or other liability, whether in an action of
15 * contract, tort or otherwise, arising from, out of or in connection
16 * with the software or the use or other dealings in the software.
17 *
18 * Permission to use, copy, modify, distribute, and sell this software
19 * and its documentation for any purpose is hereby granted without
20 * fee, provided that the above copyright notice appear in all copies
21 * and that both that copyright notice and this permission notice
22 * appear in supporting documentation.
23 */
24
25 #include <stdio.h>
26 #include <stdlib.h>
27
28 #include "dynlist.h"
29
30 #define LIST_CHUNK_SIZE 512
31 #define BUF_CHUNK_SIZE 512
32
33 /* For lists of pointers cast to char *. */
append_to_list(char *** list_ptr,int * list_len,int * i,char * item)34 int append_to_list(char ***list_ptr, int *list_len, int *i, char *item)
35 {
36 char **tmp_ptr;
37
38 if (*i >= *list_len)
39 {
40 *list_len += LIST_CHUNK_SIZE;
41 if (NULL == *list_ptr) {
42 tmp_ptr = malloc(sizeof(**list_ptr) * *list_len);
43 } else {
44 tmp_ptr = realloc(*list_ptr, (sizeof(**list_ptr) * *list_len));
45 }
46 if (NULL == tmp_ptr)
47 {
48 return(APPEND_FAILURE);
49 }
50 *list_ptr = tmp_ptr;
51 }
52 (*list_ptr)[*i] = item;
53 (*i)++;
54 return(APPEND_SUCCESS);
55 }
56
57 /* For single-dimensional buffers. */
append_to_buf(char ** buf,int * buflen,int * i,int c)58 int append_to_buf(char **buf, int *buflen, int *i, int c)
59 {
60 char *tmp_buf;
61
62 if (*i >= *buflen)
63 {
64 *buflen += BUF_CHUNK_SIZE;
65 if (NULL == *buf) {
66 tmp_buf = malloc(sizeof(**buf) * *buflen);
67 } else {
68 tmp_buf = realloc(*buf, (sizeof(**buf) * *buflen));
69 }
70 if (NULL == tmp_buf)
71 {
72 return(APPEND_FAILURE);
73 }
74 *buf = tmp_buf;
75 #ifdef DEBUG
76 printf("-->Allocated buffer of size %d\n", *buflen);
77 #endif /* DEBUG */
78 }
79 (*buf)[*i] = (char) c;
80 (*i)++;
81 return(APPEND_SUCCESS);
82 }
83
84