2 * Copyright © 2006,2007,2008 Pierre Habouzit
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. The names of its contributors may not be used to endorse or promote
14 * products derived from this software without specific prior written
17 * THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
18 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
25 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
30 #include "common/buffer.h"
38 buffer_ensure(buffer_t
*buf
, int newlen
)
43 if (newlen
< buf
->size
)
46 if (newlen
< buf
->offs
+ buf
->size
&& buf
->offs
> buf
->size
/ 4)
48 /* Data fits in the current area, shift it left */
49 memmove(buf
->s
- buf
->offs
, buf
->s
, buf
->len
+ 1);
51 buf
->size
+= buf
->offs
;
56 buf
->size
= p_alloc_nr(buf
->size
+ buf
->offs
);
57 if (buf
->size
< newlen
+ 1)
58 buf
->size
= newlen
+ 1;
59 if (buf
->alloced
&& !buf
->offs
)
60 p_realloc(&buf
->s
, buf
->size
);
63 char *new_area
= xmalloc(buf
->size
);
64 memcpy(new_area
, buf
->s
, buf
->len
+ 1);
66 free(buf
->s
- buf
->offs
);
74 buffer_addvf(buffer_t
*buf
, const char *fmt
, va_list args
)
80 buffer_ensure(buf
, BUFSIZ
);
82 len
= vsnprintf(buf
->s
+ buf
->len
, buf
->size
- buf
->len
, fmt
, args
);
83 if (unlikely(len
< 0))
85 if (len
>= buf
->size
- buf
->len
)
87 buffer_ensure(buf
, len
);
88 vsnprintf(buf
->s
+ buf
->len
, buf
->size
- buf
->len
, fmt
, ap
);
91 buf
->s
[buf
->len
] = '\0';
95 buffer_addf(buffer_t
*buf
, const char *fmt
, ...)
99 buffer_addvf(buf
, fmt
, args
);
103 /** Detach the data from a buffer.
104 * \param Buffer from which detach.
108 buffer_detach(buffer_t
*buf
)
112 res
= a_strdup(buf
->s
);