2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: wrbuf.c,v 1.8 2005-06-25 15:46:06 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 int wrbuf_xmlputs(WRBUF b, const char *cp)
86 return wrbuf_xmlputs_n(b, cp, strlen(cp));
89 int wrbuf_xmlputs_n(WRBUF b, const char *cp, int size)
93 /* only TAB,CR,LF of ASCII CTRL are allowed in XML 1.0! */
94 if (*cp >= 0 && *cp <= 31)
95 if (*cp != 9 && *cp != 10 && *cp != 13)
97 cp++; /* we silently ignore (delete) these.. */
103 wrbuf_puts(b, "<");
106 wrbuf_puts(b, ">");
109 wrbuf_puts(b, "&");
112 wrbuf_puts(b, """);
115 wrbuf_puts(b, "'");
127 void wrbuf_printf(WRBUF b, const char *fmt, ...)
134 _vsnprintf(buf, sizeof(buf)-1, fmt, ap);
138 vsnprintf(buf, sizeof(buf)-1, fmt, ap);
140 vsprintf(buf, fmt, ap);
148 static int wrbuf_iconv_write_x(WRBUF b, yaz_iconv_t cd, const char *buf,
154 size_t inbytesleft = size;
155 const char *inp = buf;
158 size_t outbytesleft = sizeof(outbuf);
160 size_t r = yaz_iconv(cd, (char**) &inp, &inbytesleft,
161 &outp, &outbytesleft);
162 if (r == (size_t) (-1))
164 int e = yaz_iconv_error(cd);
165 if (e != YAZ_ICONV_E2BIG)
169 wrbuf_xmlputs_n(b, outbuf, outp - outbuf);
171 wrbuf_write(b, outbuf, outp - outbuf);
177 wrbuf_xmlputs_n(b, buf, size);
179 wrbuf_write(b, buf, size);
184 int wrbuf_iconv_write(WRBUF b, yaz_iconv_t cd, const char *buf, int size)
186 return wrbuf_iconv_write_x(b, cd, buf, size, 0);
189 int wrbuf_iconv_write_cdata(WRBUF b, yaz_iconv_t cd, const char *buf, int size)
191 return wrbuf_iconv_write_x(b, cd, buf, size, 1);
197 * indent-tabs-mode: nil
199 * vim: shiftwidth=4 tabstop=8 expandtab