comparison src/buffer.c @ 125:e413158cae13

Add ushare project files.
author naoyan@johnstown.minaminoshima.org
date Sun, 03 Oct 2010 11:35:19 +0900
parents
children
comparison
equal deleted inserted replaced
124:9c7bc6c0327e 125:e413158cae13
1 /* buffer.c - String buffer manipulation tools.
2 * Originally developped for the GeeXboX project.
3 * Copyright (C) 2005-2007 Benjamin Zores <ben@geexbox.org>
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 2 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 Library General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 *
19 */
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <stdarg.h>
24 #include <string.h>
25
26 #include "buffer.h"
27 #include "minmax.h"
28
29 #define BUFFER_DEFAULT_CAPACITY 32768
30
31 struct buffer_t *
32 buffer_new (void)
33 {
34 struct buffer_t *buffer = NULL;
35
36 buffer = (struct buffer_t *) malloc (sizeof (struct buffer_t));
37 if (!buffer)
38 return NULL;
39
40 buffer->buf = NULL;
41 buffer->len = 0;
42 buffer->capacity = 0;
43
44 return buffer;
45 }
46
47 void
48 buffer_append (struct buffer_t *buffer, const char *str)
49 {
50 size_t len;
51
52 if (!buffer || !str)
53 return;
54
55 if (!buffer->buf)
56 {
57 buffer->capacity = BUFFER_DEFAULT_CAPACITY;
58 buffer->buf = (char *) malloc (buffer->capacity * sizeof (char));
59 memset (buffer->buf, '\0', buffer->capacity);
60 }
61
62 len = buffer->len + strlen (str);
63 if (len >= buffer->capacity)
64 {
65 buffer->capacity = MAX (len + 1, 2 * buffer->capacity);
66 buffer->buf = realloc (buffer->buf, buffer->capacity);
67 }
68
69 strcat (buffer->buf, str);
70 buffer->len += strlen (str);
71 }
72
73 void
74 buffer_appendf (struct buffer_t *buffer, const char *format, ...)
75 {
76 char str[BUFFER_DEFAULT_CAPACITY];
77 int size;
78 va_list va;
79
80 if (!buffer || !format)
81 return;
82
83 va_start (va, format);
84 size = vsnprintf (str, BUFFER_DEFAULT_CAPACITY, format, va);
85 if (size >= BUFFER_DEFAULT_CAPACITY)
86 {
87 char* dynstr = (char *) malloc (size + 1);
88 vsnprintf (dynstr, size + 1, format, va);
89 buffer_append (buffer, dynstr);
90 free (dynstr);
91 }
92 else
93 buffer_append (buffer, str);
94 va_end (va);
95 }
96
97 void
98 buffer_free (struct buffer_t *buffer)
99 {
100 if (!buffer)
101 return;
102
103 if (buffer->buf)
104 free (buffer->buf);
105 free (buffer);
106 }