1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2006-2007 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library 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 GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
21 * Christian Kellner <gicmo@gnome.org>
22 * Krzysztof KosiĆski <tweenk.pl@gmail.com>
26 #include "gmemoryoutputstream.h"
27 #include "goutputstream.h"
28 #include "gpollableoutputstream.h"
29 #include "gseekable.h"
37 * SECTION:gmemoryoutputstream
38 * @short_description: Streaming output operations on memory chunks
40 * @see_also: #GMemoryInputStream
42 * #GMemoryOutputStream is a class for using arbitrary
43 * memory chunks as output for GIO streaming output operations.
45 * As of GLib 2.34, #GMemoryOutputStream trivially implements
46 * #GPollableOutputStream: it always polls as ready.
49 #define MIN_ARRAY_SIZE 16
56 PROP_REALLOC_FUNCTION,
60 struct _GMemoryOutputStreamPrivate
62 gpointer data; /* Write buffer */
63 gsize len; /* Current length of the data buffer. Can change with resizing. */
64 gsize valid_len; /* The part of data that has been written to */
65 gsize pos; /* Current position in the stream. Distinct from valid_len,
66 because the stream is seekable. */
68 GReallocFunc realloc_fn;
69 GDestroyNotify destroy;
72 static void g_memory_output_stream_set_property (GObject *object,
76 static void g_memory_output_stream_get_property (GObject *object,
80 static void g_memory_output_stream_finalize (GObject *object);
82 static gssize g_memory_output_stream_write (GOutputStream *stream,
85 GCancellable *cancellable,
88 static gboolean g_memory_output_stream_close (GOutputStream *stream,
89 GCancellable *cancellable,
92 static void g_memory_output_stream_close_async (GOutputStream *stream,
94 GCancellable *cancellable,
95 GAsyncReadyCallback callback,
97 static gboolean g_memory_output_stream_close_finish (GOutputStream *stream,
101 static void g_memory_output_stream_seekable_iface_init (GSeekableIface *iface);
102 static goffset g_memory_output_stream_tell (GSeekable *seekable);
103 static gboolean g_memory_output_stream_can_seek (GSeekable *seekable);
104 static gboolean g_memory_output_stream_seek (GSeekable *seekable,
107 GCancellable *cancellable,
109 static gboolean g_memory_output_stream_can_truncate (GSeekable *seekable);
110 static gboolean g_memory_output_stream_truncate (GSeekable *seekable,
112 GCancellable *cancellable,
115 static gboolean g_memory_output_stream_is_writable (GPollableOutputStream *stream);
116 static GSource *g_memory_output_stream_create_source (GPollableOutputStream *stream,
117 GCancellable *cancellable);
119 static void g_memory_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface);
121 G_DEFINE_TYPE_WITH_CODE (GMemoryOutputStream, g_memory_output_stream, G_TYPE_OUTPUT_STREAM,
122 G_ADD_PRIVATE (GMemoryOutputStream)
123 G_IMPLEMENT_INTERFACE (G_TYPE_SEEKABLE,
124 g_memory_output_stream_seekable_iface_init);
125 G_IMPLEMENT_INTERFACE (G_TYPE_POLLABLE_OUTPUT_STREAM,
126 g_memory_output_stream_pollable_iface_init))
130 g_memory_output_stream_class_init (GMemoryOutputStreamClass *klass)
132 GOutputStreamClass *ostream_class;
133 GObjectClass *gobject_class;
135 gobject_class = G_OBJECT_CLASS (klass);
136 gobject_class->set_property = g_memory_output_stream_set_property;
137 gobject_class->get_property = g_memory_output_stream_get_property;
138 gobject_class->finalize = g_memory_output_stream_finalize;
140 ostream_class = G_OUTPUT_STREAM_CLASS (klass);
142 ostream_class->write_fn = g_memory_output_stream_write;
143 ostream_class->close_fn = g_memory_output_stream_close;
144 ostream_class->close_async = g_memory_output_stream_close_async;
145 ostream_class->close_finish = g_memory_output_stream_close_finish;
148 * GMemoryOutputStream:data:
150 * Pointer to buffer where data will be written.
154 g_object_class_install_property (gobject_class,
156 g_param_spec_pointer ("data",
158 P_("Pointer to buffer where data will be written."),
159 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
160 G_PARAM_STATIC_STRINGS));
163 * GMemoryOutputStream:size:
165 * Current size of the data buffer.
169 g_object_class_install_property (gobject_class,
171 g_param_spec_ulong ("size",
172 P_("Data Buffer Size"),
173 P_("Current size of the data buffer."),
175 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
176 G_PARAM_STATIC_STRINGS));
179 * GMemoryOutputStream:data-size:
181 * Size of data written to the buffer.
185 g_object_class_install_property (gobject_class,
187 g_param_spec_ulong ("data-size",
189 P_("Size of data written to the buffer."),
192 G_PARAM_STATIC_STRINGS));
195 * GMemoryOutputStream:realloc-function: (skip)
197 * Function with realloc semantics called to enlarge the buffer.
201 g_object_class_install_property (gobject_class,
202 PROP_REALLOC_FUNCTION,
203 g_param_spec_pointer ("realloc-function",
204 P_("Memory Reallocation Function"),
205 P_("Function with realloc semantics called to enlarge the buffer."),
206 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
207 G_PARAM_STATIC_STRINGS));
210 * GMemoryOutputStream:destroy-function: (skip)
212 * Function called with the buffer as argument when the stream is destroyed.
216 g_object_class_install_property (gobject_class,
217 PROP_DESTROY_FUNCTION,
218 g_param_spec_pointer ("destroy-function",
219 P_("Destroy Notification Function"),
220 P_("Function called with the buffer as argument when the stream is destroyed."),
221 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
222 G_PARAM_STATIC_STRINGS));
226 g_memory_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface)
228 iface->is_writable = g_memory_output_stream_is_writable;
229 iface->create_source = g_memory_output_stream_create_source;
233 g_memory_output_stream_set_property (GObject *object,
238 GMemoryOutputStream *stream;
239 GMemoryOutputStreamPrivate *priv;
241 stream = G_MEMORY_OUTPUT_STREAM (object);
247 priv->data = g_value_get_pointer (value);
250 priv->len = g_value_get_ulong (value);
252 case PROP_REALLOC_FUNCTION:
253 priv->realloc_fn = g_value_get_pointer (value);
255 case PROP_DESTROY_FUNCTION:
256 priv->destroy = g_value_get_pointer (value);
259 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
265 g_memory_output_stream_get_property (GObject *object,
270 GMemoryOutputStream *stream;
271 GMemoryOutputStreamPrivate *priv;
273 stream = G_MEMORY_OUTPUT_STREAM (object);
279 g_value_set_pointer (value, priv->data);
282 g_value_set_ulong (value, priv->len);
285 g_value_set_ulong (value, priv->valid_len);
287 case PROP_REALLOC_FUNCTION:
288 g_value_set_pointer (value, priv->realloc_fn);
290 case PROP_DESTROY_FUNCTION:
291 g_value_set_pointer (value, priv->destroy);
294 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
300 g_memory_output_stream_finalize (GObject *object)
302 GMemoryOutputStream *stream;
303 GMemoryOutputStreamPrivate *priv;
305 stream = G_MEMORY_OUTPUT_STREAM (object);
309 priv->destroy (priv->data);
311 G_OBJECT_CLASS (g_memory_output_stream_parent_class)->finalize (object);
315 g_memory_output_stream_seekable_iface_init (GSeekableIface *iface)
317 iface->tell = g_memory_output_stream_tell;
318 iface->can_seek = g_memory_output_stream_can_seek;
319 iface->seek = g_memory_output_stream_seek;
320 iface->can_truncate = g_memory_output_stream_can_truncate;
321 iface->truncate_fn = g_memory_output_stream_truncate;
326 g_memory_output_stream_init (GMemoryOutputStream *stream)
328 stream->priv = g_memory_output_stream_get_instance_private (stream);
329 stream->priv->pos = 0;
330 stream->priv->valid_len = 0;
334 * g_memory_output_stream_new: (skip)
335 * @data: (allow-none): pointer to a chunk of memory to use, or %NULL
336 * @size: the size of @data
337 * @realloc_function: (allow-none): a function with realloc() semantics (like g_realloc())
338 * to be called when @data needs to be grown, or %NULL
339 * @destroy_function: (allow-none): a function to be called on @data when the stream is
340 * finalized, or %NULL
342 * Creates a new #GMemoryOutputStream.
344 * In most cases this is not the function you want. See
345 * g_memory_output_stream_new_resizable() instead.
347 * If @data is non-%NULL, the stream will use that for its internal storage.
349 * If @realloc_fn is non-%NULL, it will be used for resizing the internal
350 * storage when necessary and the stream will be considered resizable.
351 * In that case, the stream will start out being (conceptually) empty.
352 * @size is used only as a hint for how big @data is. Specifically,
353 * seeking to the end of a newly-created stream will seek to zero, not
354 * @size. Seeking past the end of the stream and then writing will
355 * introduce a zero-filled gap.
357 * If @realloc_fn is %NULL then the stream is fixed-sized. Seeking to
358 * the end will seek to @size exactly. Writing past the end will give
359 * an 'out of space' error. Attempting to seek past the end will fail.
360 * Unlike the resizable case, seeking to an offset within the stream and
361 * writing will preserve the bytes passed in as @data before that point
362 * and will return them as part of g_memory_output_stream_steal_data().
363 * If you intend to seek you should probably therefore ensure that @data
364 * is properly initialised.
366 * It is probably only meaningful to provide @data and @size in the case
367 * that you want a fixed-sized stream. Put another way: if @realloc_fn
368 * is non-%NULL then it makes most sense to give @data as %NULL and
369 * @size as 0 (allowing #GMemoryOutputStream to do the initial
370 * allocation for itself).
373 * /* a stream that can grow */
374 * stream = g_memory_output_stream_new (NULL, 0, realloc, free);
376 * /* another stream that can grow */
377 * stream2 = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
379 * /* a fixed-size stream */
380 * data = malloc (200);
381 * stream3 = g_memory_output_stream_new (data, 200, NULL, free);
384 * Return value: A newly created #GMemoryOutputStream object.
387 g_memory_output_stream_new (gpointer data,
389 GReallocFunc realloc_function,
390 GDestroyNotify destroy_function)
392 GOutputStream *stream;
394 stream = g_object_new (G_TYPE_MEMORY_OUTPUT_STREAM,
397 "realloc-function", realloc_function,
398 "destroy-function", destroy_function,
405 * g_memory_output_stream_new_resizable:
407 * Creates a new #GMemoryOutputStream, using g_realloc() and g_free()
408 * for memory allocation.
413 g_memory_output_stream_new_resizable (void)
415 return g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
419 * g_memory_output_stream_get_data:
420 * @ostream: a #GMemoryOutputStream
422 * Gets any loaded data from the @ostream.
424 * Note that the returned pointer may become invalid on the next
425 * write or truncate operation on the stream.
427 * Returns: (transfer none): pointer to the stream's data
430 g_memory_output_stream_get_data (GMemoryOutputStream *ostream)
432 g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
434 return ostream->priv->data;
438 * g_memory_output_stream_get_size:
439 * @ostream: a #GMemoryOutputStream
441 * Gets the size of the currently allocated data area (available from
442 * g_memory_output_stream_get_data()).
444 * You probably don't want to use this function on resizable streams.
445 * See g_memory_output_stream_get_data_size() instead. For resizable
446 * streams the size returned by this function is an implementation
447 * detail and may be change at any time in response to operations on the
450 * If the stream is fixed-sized (ie: no realloc was passed to
451 * g_memory_output_stream_new()) then this is the maximum size of the
452 * stream and further writes will return %G_IO_ERROR_NO_SPACE.
454 * In any case, if you want the number of bytes currently written to the
455 * stream, use g_memory_output_stream_get_data_size().
457 * Returns: the number of bytes allocated for the data buffer
460 g_memory_output_stream_get_size (GMemoryOutputStream *ostream)
462 g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
464 return ostream->priv->len;
468 * g_memory_output_stream_get_data_size:
469 * @ostream: a #GMemoryOutputStream
471 * Returns the number of bytes from the start up to including the last
472 * byte written in the stream that has not been truncated away.
474 * Returns: the number of bytes written to the stream
479 g_memory_output_stream_get_data_size (GMemoryOutputStream *ostream)
481 g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
483 return ostream->priv->valid_len;
487 * g_memory_output_stream_steal_data:
488 * @ostream: a #GMemoryOutputStream
490 * Gets any loaded data from the @ostream. Ownership of the data
491 * is transferred to the caller; when no longer needed it must be
492 * freed using the free function set in @ostream's
493 * #GMemoryOutputStream:destroy-function property.
495 * @ostream must be closed before calling this function.
497 * Returns: (transfer full): the stream's data
502 g_memory_output_stream_steal_data (GMemoryOutputStream *ostream)
506 g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
507 g_return_val_if_fail (g_output_stream_is_closed (G_OUTPUT_STREAM (ostream)), NULL);
509 data = ostream->priv->data;
510 ostream->priv->data = NULL;
516 * g_memory_output_stream_steal_as_bytes:
517 * @ostream: a #GMemoryOutputStream
519 * Returns data from the @ostream as a #GBytes. @ostream must be
520 * closed before calling this function.
522 * Returns: (transfer full): the stream's data
527 g_memory_output_stream_steal_as_bytes (GMemoryOutputStream *ostream)
531 g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
532 g_return_val_if_fail (g_output_stream_is_closed (G_OUTPUT_STREAM (ostream)), NULL);
534 result = g_bytes_new_with_free_func (ostream->priv->data,
535 ostream->priv->valid_len,
536 ostream->priv->destroy,
537 ostream->priv->data);
538 ostream->priv->data = NULL;
544 array_resize (GMemoryOutputStream *ostream,
546 gboolean allow_partial,
549 GMemoryOutputStreamPrivate *priv;
553 priv = ostream->priv;
555 if (priv->len == size)
558 if (!priv->realloc_fn)
561 priv->pos < priv->len)
562 return TRUE; /* Short write */
564 g_set_error_literal (error,
567 _("Memory output stream not resizable"));
572 data = priv->realloc_fn (priv->data, size);
574 if (size > 0 && !data)
577 priv->pos < priv->len)
578 return TRUE; /* Short write */
580 g_set_error_literal (error,
583 _("Failed to resize memory output stream"));
588 memset ((guint8 *)data + len, 0, size - len);
593 if (priv->len < priv->valid_len)
594 priv->valid_len = priv->len;
600 g_nearest_pow (gint num)
611 g_memory_output_stream_write (GOutputStream *stream,
614 GCancellable *cancellable,
617 GMemoryOutputStream *ostream;
618 GMemoryOutputStreamPrivate *priv;
622 ostream = G_MEMORY_OUTPUT_STREAM (stream);
623 priv = ostream->priv;
628 /* Check for address space overflow, but only if the buffer is resizable.
629 Otherwise we just do a short write and don't worry. */
630 if (priv->realloc_fn && priv->pos + count < priv->pos)
633 if (priv->pos + count > priv->len)
635 /* At least enough to fit the write, rounded up for greater than
638 * Assuming that we're using something like realloc(), the kernel
639 * will overcommit memory to us, so doubling the size each time
640 * will keep the number of realloc calls low without wasting too
643 new_size = g_nearest_pow (priv->pos + count);
644 /* Check for overflow again. We have only checked if
645 pos + count > G_MAXSIZE, but it only catches the case of writing
646 more than 4GiB total on a 32-bit system. There's still the problem
647 of g_nearest_pow overflowing above 0x7fffffff, so we're
648 effectively limited to 2GiB. */
649 if (new_size < priv->len)
652 new_size = MAX (new_size, MIN_ARRAY_SIZE);
653 if (!array_resize (ostream, new_size, TRUE, error))
657 /* Make sure we handle short writes if the array_resize
658 only added part of the required memory */
659 count = MIN (count, priv->len - priv->pos);
661 dest = (guint8 *)priv->data + priv->pos;
662 memcpy (dest, buffer, count);
665 if (priv->pos > priv->valid_len)
666 priv->valid_len = priv->pos;
671 /* Overflow: buffer size would need to be bigger than G_MAXSIZE. */
672 g_set_error_literal (error,
675 _("Amount of memory required to process the write is "
676 "larger than available address space"));
681 g_memory_output_stream_close (GOutputStream *stream,
682 GCancellable *cancellable,
689 g_memory_output_stream_close_async (GOutputStream *stream,
691 GCancellable *cancellable,
692 GAsyncReadyCallback callback,
697 task = g_task_new (stream, cancellable, callback, data);
699 /* will always return TRUE */
700 g_memory_output_stream_close (stream, cancellable, NULL);
702 g_task_return_boolean (task, TRUE);
703 g_object_unref (task);
707 g_memory_output_stream_close_finish (GOutputStream *stream,
708 GAsyncResult *result,
711 g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
713 return g_task_propagate_boolean (G_TASK (result), error);
717 g_memory_output_stream_tell (GSeekable *seekable)
719 GMemoryOutputStream *stream;
720 GMemoryOutputStreamPrivate *priv;
722 stream = G_MEMORY_OUTPUT_STREAM (seekable);
729 g_memory_output_stream_can_seek (GSeekable *seekable)
735 g_memory_output_stream_seek (GSeekable *seekable,
738 GCancellable *cancellable,
741 GMemoryOutputStream *stream;
742 GMemoryOutputStreamPrivate *priv;
745 stream = G_MEMORY_OUTPUT_STREAM (seekable);
751 absolute = priv->pos + offset;
759 /* For resizable streams, we consider the end to be the data
760 * length. For fixed-sized streams, we consider the end to be the
761 * size of the buffer.
763 if (priv->realloc_fn)
764 absolute = priv->valid_len + offset;
766 absolute = priv->len + offset;
770 g_set_error_literal (error,
772 G_IO_ERROR_INVALID_ARGUMENT,
773 _("Invalid GSeekType supplied"));
780 g_set_error_literal (error,
782 G_IO_ERROR_INVALID_ARGUMENT,
783 _("Requested seek before the beginning of the stream"));
787 /* Can't seek past the end of a fixed-size stream.
789 * Note: seeking to the non-existent byte at the end of a fixed-sized
790 * stream is valid (eg: a 1-byte fixed sized stream can have position
791 * 0 or 1). Therefore '>' is what we want.
793 if (priv->realloc_fn == NULL && absolute > priv->len)
795 g_set_error_literal (error,
797 G_IO_ERROR_INVALID_ARGUMENT,
798 _("Requested seek beyond the end of the stream"));
802 priv->pos = absolute;
808 g_memory_output_stream_can_truncate (GSeekable *seekable)
810 GMemoryOutputStream *ostream;
811 GMemoryOutputStreamPrivate *priv;
813 ostream = G_MEMORY_OUTPUT_STREAM (seekable);
814 priv = ostream->priv;
816 /* We do not allow truncation of fixed-sized streams */
817 return priv->realloc_fn != NULL;
821 g_memory_output_stream_truncate (GSeekable *seekable,
823 GCancellable *cancellable,
826 GMemoryOutputStream *ostream = G_MEMORY_OUTPUT_STREAM (seekable);
828 if (!array_resize (ostream, offset, FALSE, error))
831 ostream->priv->valid_len = offset;
837 g_memory_output_stream_is_writable (GPollableOutputStream *stream)
843 g_memory_output_stream_create_source (GPollableOutputStream *stream,
844 GCancellable *cancellable)
846 GSource *base_source, *pollable_source;
848 base_source = g_timeout_source_new (0);
849 pollable_source = g_pollable_source_new_full (stream, base_source, cancellable);
850 g_source_unref (base_source);
852 return pollable_source;