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.
34 #include "common/buffer.h"
39 buffer_ensure(buffer_t
*buf
, int newlen
)
44 if (newlen
< buf
->size
)
47 if (newlen
< buf
->offs
+ buf
->size
&& buf
->offs
> buf
->size
/ 4)
49 /* Data fits in the current area, shift it left */
50 memmove(buf
->s
- buf
->offs
, buf
->s
, buf
->len
+ 1);
52 buf
->size
+= buf
->offs
;
57 buf
->size
= p_alloc_nr(buf
->size
+ buf
->offs
);
58 if (buf
->size
< newlen
+ 1)
59 buf
->size
= newlen
+ 1;
60 if (buf
->alloced
&& !buf
->offs
)
61 p_realloc(&buf
->s
, buf
->size
);
64 char *new_area
= xmalloc(buf
->size
);
65 memcpy(new_area
, buf
->s
, buf
->len
+ 1);
67 free(buf
->s
- buf
->offs
);
75 buffer_addvf(buffer_t
*buf
, const char *fmt
, va_list args
)
81 buffer_ensure(buf
, BUFSIZ
);
83 len
= vsnprintf(buf
->s
+ buf
->len
, buf
->size
- buf
->len
, fmt
, args
);
84 if (unlikely(len
< 0))
86 if (len
>= buf
->size
- buf
->len
)
88 buffer_ensure(buf
, len
);
89 vsnprintf(buf
->s
+ buf
->len
, buf
->size
- buf
->len
, fmt
, ap
);
92 buf
->s
[buf
->len
] = '\0';
96 buffer_addf(buffer_t
*buf
, const char *fmt
, ...)
100 buffer_addvf(buf
, fmt
, args
);
104 /** Detach the data from a buffer.
105 * \param Buffer from which detach.
109 buffer_detach(buffer_t
*buf
)
113 res
= a_strdup(buf
->s
);