Mercurial > hg > dmlib
comparison dmstring.c @ 0:32250b436bca
Initial re-import.
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Fri, 28 Sep 2012 01:54:23 +0300 |
parents | |
children | 2726d91e3409 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:32250b436bca |
---|---|
1 #include "dmlib.h" | |
2 #include <stdarg.h> | |
3 | |
4 /* strdup with a NULL check | |
5 */ | |
6 char *dm_strdup(const char *s) | |
7 { | |
8 char *res; | |
9 if (s == NULL) | |
10 return NULL; | |
11 | |
12 if ((res = dmMalloc(strlen(s) + 1)) == NULL) | |
13 return NULL; | |
14 | |
15 strcpy(res, s); | |
16 return res; | |
17 } | |
18 | |
19 | |
20 /* Simulate a sprintf() that allocates memory | |
21 */ | |
22 char *dm_strdup_vprintf(const char *fmt, va_list args) | |
23 { | |
24 int size = 64; | |
25 char *buf; | |
26 | |
27 if ((buf = dmMalloc(size)) == NULL) | |
28 return NULL; | |
29 | |
30 while (1) | |
31 { | |
32 int n; | |
33 va_list ap; | |
34 va_copy(ap, args); | |
35 n = vsnprintf(buf, size, fmt, ap); | |
36 va_end(ap); | |
37 | |
38 if (n > -1 && n < size) | |
39 return buf; | |
40 if (n > -1) | |
41 size = n + 1; | |
42 else | |
43 size *= 2; | |
44 | |
45 if ((buf = dmRealloc(buf, size)) == NULL) | |
46 return NULL; | |
47 } | |
48 } | |
49 | |
50 | |
51 char *dm_strdup_printf(const char *fmt, ...) | |
52 { | |
53 char *res; | |
54 va_list ap; | |
55 | |
56 va_start(ap, fmt); | |
57 res = dm_strdup_vprintf(fmt, ap); | |
58 va_end(ap); | |
59 | |
60 return res; | |
61 } |