Added some string utility functions.
[ashd.git] / lib / utils.c
1 /*
2     ashd - A Sane HTTP Daemon
3     Copyright (C) 2008  Fredrik Tolf <fredrik@dolda2000.com>
4
5     This program is free software: you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation, either version 3 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <stdlib.h>
20 #include <stdio.h>
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25 #include <utils.h>
26
27 void _sizebuf(struct buffer *buf, size_t wanted, size_t el)
28 {
29     size_t n;
30     
31     n = buf->s;
32     if(n == 0)
33         n = 1;
34     while(n < wanted)
35         n <<= 1;
36     if(n <= buf->s)
37         return;
38     if(buf->b != NULL)
39         buf->b = srealloc(buf->b, n * el);
40     else
41         buf->b = smalloc(n * el);
42     buf->s = n;
43 }
44
45 char *decstr(char **p, size_t *len)
46 {
47     char *p2, *ret;
48     
49     for(p2 = *p; (p2 - *p) < *len; p2++) {
50         if(*p2 == 0)
51             break;
52     }
53     if((p2 - *p) == *len)
54         return(NULL);
55     p2++;
56     ret = *p;
57     *len -= p2 - *p;
58     *p = p2;
59     return(ret);
60 }
61
62 char *vsprintf2(char *format, va_list al)
63 {
64     int ret;
65     char *buf;
66     va_list al2;
67     
68     va_copy(al2, al);
69     ret = vsnprintf(NULL, 0, format, al2);
70     va_end(al2);
71     buf = smalloc(ret + 1);
72     va_copy(al2, al);
73     vsnprintf(buf, ret + 1, format, al2);
74     va_end(al2);
75     return(buf);
76 }
77
78 char *sprintf2(char *format, ...)
79 {
80     va_list args;
81     char *buf;
82     
83     va_start(args, format);
84     buf = vsprintf2(format, args);
85     va_end(args);
86     return(buf);
87 }
88
89 char *sprintf3(char *format, ...)
90 {
91     static char *buf = NULL;
92     va_list args;
93     
94     if(buf != NULL)
95         free(buf);
96     va_start(args, format);
97     buf = vsprintf2(format, args);
98     va_end(args);
99     return(buf);
100 }