2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: wrbuf.c,v 1.10 2006-04-19 10:05:03 adam Exp $
10 * \brief Implements WRBUF (growing buffer)
22 #include <yaz/wrbuf.h>
23 #include <yaz/yaz-iconv.h>
25 WRBUF wrbuf_alloc(void)
29 if (!(n = (WRBUF)xmalloc(sizeof(*n))))
37 void wrbuf_free(WRBUF b, int free_buf)
39 if (free_buf && b->buf)
44 void wrbuf_rewind(WRBUF b)
49 int wrbuf_grow(WRBUF b, int minsize)
59 if (b->size && !(b->buf =(char *)xrealloc(b->buf, b->size += togrow)))
61 else if (!b->size && !(b->buf = (char *)xmalloc(b->size = togrow)))
66 int wrbuf_write(WRBUF b, const char *buf, int size)
70 if (b->pos + size >= b->size)
72 memcpy(b->buf + b->pos, buf, size);
77 int wrbuf_puts(WRBUF b, const char *buf)
79 wrbuf_write(b, buf, strlen(buf)+1); /* '\0'-terminate as well */
80 (b->pos)--; /* don't include '\0' in count */
84 void wrbuf_chop_right(WRBUF b)
86 while (b->pos && b->buf[b->pos-1] == ' ')
89 b->buf[b->pos] = '\0';
93 int wrbuf_xmlputs(WRBUF b, const char *cp)
95 return wrbuf_xmlputs_n(b, cp, strlen(cp));
98 int wrbuf_xmlputs_n(WRBUF b, const char *cp, int size)
102 /* only TAB,CR,LF of ASCII CTRL are allowed in XML 1.0! */
103 if (*cp >= 0 && *cp <= 31)
104 if (*cp != 9 && *cp != 10 && *cp != 13)
106 cp++; /* we silently ignore (delete) these.. */
112 wrbuf_puts(b, "<");
115 wrbuf_puts(b, ">");
118 wrbuf_puts(b, "&");
121 wrbuf_puts(b, """);
124 wrbuf_puts(b, "'");
136 void wrbuf_printf(WRBUF b, const char *fmt, ...)
143 _vsnprintf(buf, sizeof(buf)-1, fmt, ap);
147 vsnprintf(buf, sizeof(buf)-1, fmt, ap);
149 vsprintf(buf, fmt, ap);
157 static int wrbuf_iconv_write_x(WRBUF b, yaz_iconv_t cd, const char *buf,
163 size_t inbytesleft = size;
164 const char *inp = buf;
167 size_t outbytesleft = sizeof(outbuf);
169 size_t r = yaz_iconv(cd, (char**) &inp, &inbytesleft,
170 &outp, &outbytesleft);
171 if (r == (size_t) (-1))
173 int e = yaz_iconv_error(cd);
174 if (e != YAZ_ICONV_E2BIG)
178 wrbuf_xmlputs_n(b, outbuf, outp - outbuf);
180 wrbuf_write(b, outbuf, outp - outbuf);
186 wrbuf_xmlputs_n(b, buf, size);
188 wrbuf_write(b, buf, size);
193 int wrbuf_iconv_write(WRBUF b, yaz_iconv_t cd, const char *buf, int size)
195 return wrbuf_iconv_write_x(b, cd, buf, size, 0);
198 int wrbuf_iconv_puts(WRBUF b, yaz_iconv_t cd, const char *strz)
200 return wrbuf_iconv_write(b, cd, strz, strlen(strz));
203 int wrbuf_iconv_write_cdata(WRBUF b, yaz_iconv_t cd, const char *buf, int size)
205 return wrbuf_iconv_write_x(b, cd, buf, size, 1);
211 * indent-tabs-mode: nil
213 * vim: shiftwidth=4 tabstop=8 expandtab