1 /* Output stream that accumulates the output in memory.
2 Copyright (C) 2006-2007 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2006.
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 3 of the License, or
8 (at your option) any later version.
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 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include "memory-ostream.h"
31 #define _(str) gettext (str)
33 struct memory_ostream : struct ostream
36 char *buffer; /* Buffer containing the accumulated output. */
37 size_t buflen; /* Number of bytes stored so far. */
38 size_t allocated; /* Allocated size of the buffer. */
41 /* Implementation of ostream_t methods. */
44 memory_ostream::write_mem (memory_ostream_t stream,
45 const void *data, size_t len)
49 if (len > stream->allocated - stream->buflen)
51 size_t new_allocated =
52 xmax (xsum (stream->buflen, len),
53 xsum (stream->allocated, stream->allocated));
54 if (size_overflow_p (new_allocated))
55 error (EXIT_FAILURE, 0,
56 _("%s: too much output, buffer size overflow"),
58 stream->buffer = (char *) xrealloc (stream->buffer, new_allocated);
59 stream->allocated = new_allocated;
61 memcpy (stream->buffer + stream->buflen, data, len);
62 stream->buflen += len;
67 memory_ostream::flush (memory_ostream_t stream)
72 memory_ostream::free (memory_ostream_t stream)
74 free (stream->buffer);
78 /* Implementation of memory_ostream_t methods. */
81 memory_ostream::contents (memory_ostream_t stream,
82 const void **bufp, size_t *buflenp)
84 *bufp = stream->buffer;
85 *buflenp = stream->buflen;
91 memory_ostream_create (void)
93 memory_ostream_t stream = XMALLOC (struct memory_ostream_representation);
95 stream->base.vtable = &memory_ostream_vtable;
96 stream->allocated = 250;
97 stream->buffer = XNMALLOC (stream->allocated, char);