This patch includes utility functions to support dynamically sized arrays.
[rrdtool.git] / src / rrd_utils.c
1 /**
2  * This program is free software; you can redistribute it and/or modify it
3  * under the terms of the GNU General Public License as published by the
4  * Free Software Foundation; only version 2 of the License is applicable.
5  *
6  * This program is distributed in the hope that it will be useful, but
7  * WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9  * General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public License along
12  * with this program; if not, write to the Free Software Foundation, Inc.,
13  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
14  **/
15
16 #include "rrd_tool.h"
17
18 #include <stdlib.h>
19 #include <assert.h>
20
21 #ifdef WIN32
22 #       define random() rand()
23 #       define srandom(x) srand(x)
24 #       define getpid() 0
25 #endif /* WIN32 */
26
27 /* make sure that the random number generator seeded EXACTLY ONCE */
28 long rrd_random(void)
29 {
30     static int rand_init = 0;
31     if (!rand_init) {
32         srandom((unsigned int) time(NULL) + (unsigned int) getpid());
33         rand_init++;
34     }
35
36     return random();
37 }
38
39 /* rrd_add_ptr: add a pointer to a dynamically sized array of pointers,
40  * realloc as necessary.  returns 1 on success, 0 on failure.
41  */
42
43 int rrd_add_ptr(void ***dest, size_t *dest_size, void *src)
44 {
45     void **temp;
46
47     assert(dest != NULL);
48
49     temp = (void **) rrd_realloc(*dest, (*dest_size+1) * sizeof(*dest));
50     if (!temp)
51         return 0;
52
53     *dest = temp;
54     temp[*dest_size] = src;
55     (*dest_size)++;
56
57     return 1;
58 }
59
60 /* like rrd_add_ptr, but calls strdup() on a string first. */
61 int rrd_add_strdup(char ***dest, size_t *dest_size, char *src)
62 {
63     char *dup_src;
64     int add_ok;
65
66     assert(dest != NULL);
67     assert(src  != NULL);
68
69     dup_src = strdup(src);
70     if (!dup_src)
71         return 0;
72
73     add_ok = rrd_add_ptr((void ***)dest, dest_size, (void *)dup_src);
74     if (!add_ok)
75         free(dup_src);
76
77     return add_ok;
78 }
79
80 void rrd_free_ptrs(void ***src, size_t *cnt)
81 {
82     void **sp;
83
84     assert(src != NULL);
85     sp = *src;
86
87     if (sp == NULL)
88         return;
89
90     while (*cnt > 0) {
91         (*cnt)--;
92         free(sp[*cnt]);
93     }
94
95     free (sp);
96     *src = NULL;
97 }