Initial commit of Debian packaging.
[usmb.git] / utils.c
blobbcb853e4f664003ad64431fb7a030a1f69d1eabd
1 /* usmb - mount SMB shares via FUSE and Samba
2 * Copyright (C) 2006-2009 Geoff Johnstone
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 3 as
6 * published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #include "config.h"
18 #include <assert.h>
19 #include <errno.h>
20 #include <stdarg.h>
21 #include <stddef.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include "utils.h"
29 #define INIT_LEN 256
30 char * concat_strings (int num, ...)
32 va_list ap;
34 char *base, *out;
36 base = out = malloc (INIT_LEN);
37 if (NULL == base)
38 return NULL;
40 size_t buff_size = INIT_LEN;
42 va_start (ap, num);
43 for (int i = 0; i < num; ++i)
45 const char *next = va_arg (ap, const char *);
46 assert (NULL != next);
48 size_t next_len = strlen (next);
49 /*LINTED*/
50 size_t required = (out - base) + next_len + 1;
52 if (buff_size < required)
54 while (buff_size < required)
56 size_t dbl_len = buff_size * 2;
57 if (dbl_len < buff_size)
59 free (base);
60 va_end (ap);
61 return NULL;
64 buff_size = dbl_len;
67 /*LINTED*/
68 ptrdiff_t diff = out - base;
70 char *newbase = realloc (base, buff_size);
71 if (NULL == newbase)
73 free (base);
74 va_end (ap);
75 return NULL;
78 base = newbase;
79 out = base + diff;
82 memcpy (out, next, next_len);
83 out += next_len;
85 va_end (ap);
87 *out = '\0';
88 return base;
92 char * xstrdup (const char *in)
94 char *out = NULL;
96 if (NULL != in)
98 size_t len = strlen (in) + 1;
100 if ((out = malloc (len)))
101 memcpy (out, in, len);
104 return out;
108 // the const here lets us pass a pointer to const
109 void xfree (const void *ptr)
111 if (NULL != ptr)
112 free ((void *)ptr);
116 void clear_and_free (char *ptr)
118 if (NULL != ptr)
120 for (char *pch = ptr; '\0' != *pch; ++pch)
121 *pch = '\0';
123 free (ptr);
128 void free_errno (const void *ptr)
130 int err = errno;
131 free ((void *)ptr);
132 errno = err;
136 void xfree_errno (const void *ptr)
138 int err = errno;
139 xfree (ptr);
140 errno = err;