4 This file is part of PulseAudio.
6 Copyright 2004-2006 Lennart Poettering
8 PulseAudio is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published
10 by the Free Software Foundation; either version 2 of the License,
11 or (at your option) any later version.
13 PulseAudio is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with PulseAudio; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
28 #include <sys/types.h>
34 #include <pulse/xmalloc.h>
35 #include <pulsecore/macro.h>
39 /* A chunk of the linked list that makes up the string */
45 #define CHUNK_TO_TEXT(c) ((char*) (c) + PA_ALIGN(sizeof(struct chunk)))
49 struct chunk *head, *tail;
52 pa_strbuf *pa_strbuf_new(void) {
54 pa_strbuf *sb = pa_xnew(pa_strbuf, 1);
56 sb->head = sb->tail = NULL;
61 void pa_strbuf_free(pa_strbuf *sb) {
65 struct chunk *c = sb->head;
66 sb->head = sb->head->next;
73 /* Make a C string from the string buffer. The caller has to free
74 * string with pa_xfree(). */
75 char *pa_strbuf_tostring(pa_strbuf *sb) {
81 e = t = pa_xnew(char, sb->length+1);
83 for (c = sb->head; c; c = c->next) {
84 assert((size_t) (e-t) <= sb->length);
85 memcpy(e, CHUNK_TO_TEXT(c), c->length);
92 assert(e == t+sb->length);
97 /* Combination of pa_strbuf_free() and pa_strbuf_tostring() */
98 char *pa_strbuf_tostring_free(pa_strbuf *sb) {
102 t = pa_strbuf_tostring(sb);
108 /* Append a string to the string buffer */
109 void pa_strbuf_puts(pa_strbuf *sb, const char *t) {
114 pa_strbuf_putsn(sb, t, strlen(t));
117 /* Append a new chunk to the linked list */
118 static void append(pa_strbuf *sb, struct chunk *c) {
126 pa_assert(!sb->head);
131 sb->length += c->length;
135 /* Append up to l bytes of a string to the string buffer */
136 void pa_strbuf_putsn(pa_strbuf *sb, const char *t, size_t l) {
145 c = pa_xmalloc(PA_ALIGN(sizeof(struct chunk)) + l);
147 memcpy(CHUNK_TO_TEXT(c), t, l);
152 /* Append a printf() style formatted string to the string buffer. */
153 /* The following is based on an example from the GNU libc documentation */
154 int pa_strbuf_printf(pa_strbuf *sb, const char *format, ...) {
156 struct chunk *c = NULL;
165 c = pa_xrealloc(c, PA_ALIGN(sizeof(struct chunk)) + size);
167 va_start(ap, format);
168 r = vsnprintf(CHUNK_TO_TEXT(c), size, format, ap);
169 CHUNK_TO_TEXT(c)[size-1] = 0;
172 if (r > -1 && r < size) {
178 if (r > -1) /* glibc 2.1 */