GApplication: More documentation tweaks
[glib.git] / gio / gmemoryoutputstream.c
blobb6b532d8afaf3b4386ea5f77ed4277e5051e1973
1 /* GIO - GLib Input, Output and Streaming Library
2 *
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.
20 * Authors:
21 * Christian Kellner <gicmo@gnome.org>
22 * Krzysztof KosiƄski <tweenk.pl@gmail.com>
25 #include "config.h"
26 #include "gmemoryoutputstream.h"
27 #include "goutputstream.h"
28 #include "gseekable.h"
29 #include "gsimpleasyncresult.h"
30 #include "gioerror.h"
31 #include "string.h"
32 #include "glibintl.h"
35 /**
36 * SECTION:gmemoryoutputstream
37 * @short_description: Streaming output operations on memory chunks
38 * @include: gio/gio.h
39 * @see_also: #GMemoryInputStream
41 * #GMemoryOutputStream is a class for using arbitrary
42 * memory chunks as output for GIO streaming output operations.
46 #define MIN_ARRAY_SIZE 16
48 enum {
49 PROP_0,
50 PROP_DATA,
51 PROP_SIZE,
52 PROP_DATA_SIZE,
53 PROP_REALLOC_FUNCTION,
54 PROP_DESTROY_FUNCTION
57 struct _GMemoryOutputStreamPrivate {
59 gpointer data; /* Write buffer */
60 gsize len; /* Current length of the data buffer. Can change with resizing. */
61 gsize valid_len; /* The part of data that has been written to */
62 gsize pos; /* Current position in the stream. Distinct from valid_len,
63 because the stream is seekable. */
65 GReallocFunc realloc_fn;
66 GDestroyNotify destroy;
69 static void g_memory_output_stream_set_property (GObject *object,
70 guint prop_id,
71 const GValue *value,
72 GParamSpec *pspec);
73 static void g_memory_output_stream_get_property (GObject *object,
74 guint prop_id,
75 GValue *value,
76 GParamSpec *pspec);
77 static void g_memory_output_stream_finalize (GObject *object);
79 static gssize g_memory_output_stream_write (GOutputStream *stream,
80 const void *buffer,
81 gsize count,
82 GCancellable *cancellable,
83 GError **error);
85 static gboolean g_memory_output_stream_close (GOutputStream *stream,
86 GCancellable *cancellable,
87 GError **error);
89 static void g_memory_output_stream_write_async (GOutputStream *stream,
90 const void *buffer,
91 gsize count,
92 int io_priority,
93 GCancellable *cancellable,
94 GAsyncReadyCallback callback,
95 gpointer data);
96 static gssize g_memory_output_stream_write_finish (GOutputStream *stream,
97 GAsyncResult *result,
98 GError **error);
99 static void g_memory_output_stream_close_async (GOutputStream *stream,
100 int io_priority,
101 GCancellable *cancellable,
102 GAsyncReadyCallback callback,
103 gpointer data);
104 static gboolean g_memory_output_stream_close_finish (GOutputStream *stream,
105 GAsyncResult *result,
106 GError **error);
108 static void g_memory_output_stream_seekable_iface_init (GSeekableIface *iface);
109 static goffset g_memory_output_stream_tell (GSeekable *seekable);
110 static gboolean g_memory_output_stream_can_seek (GSeekable *seekable);
111 static gboolean g_memory_output_stream_seek (GSeekable *seekable,
112 goffset offset,
113 GSeekType type,
114 GCancellable *cancellable,
115 GError **error);
116 static gboolean g_memory_output_stream_can_truncate (GSeekable *seekable);
117 static gboolean g_memory_output_stream_truncate (GSeekable *seekable,
118 goffset offset,
119 GCancellable *cancellable,
120 GError **error);
122 G_DEFINE_TYPE_WITH_CODE (GMemoryOutputStream, g_memory_output_stream, G_TYPE_OUTPUT_STREAM,
123 G_IMPLEMENT_INTERFACE (G_TYPE_SEEKABLE,
124 g_memory_output_stream_seekable_iface_init))
127 static void
128 g_memory_output_stream_class_init (GMemoryOutputStreamClass *klass)
130 GOutputStreamClass *ostream_class;
131 GObjectClass *gobject_class;
133 g_type_class_add_private (klass, sizeof (GMemoryOutputStreamPrivate));
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->write_async = g_memory_output_stream_write_async;
145 ostream_class->write_finish = g_memory_output_stream_write_finish;
146 ostream_class->close_async = g_memory_output_stream_close_async;
147 ostream_class->close_finish = g_memory_output_stream_close_finish;
150 * GMemoryOutputStream:data:
152 * Pointer to buffer where data will be written.
154 * Since: 2.24
156 g_object_class_install_property (gobject_class,
157 PROP_DATA,
158 g_param_spec_pointer ("data",
159 P_("Data Buffer"),
160 P_("Pointer to buffer where data will be written."),
161 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
162 G_PARAM_STATIC_STRINGS));
165 * GMemoryOutputStream:size:
167 * Current size of the data buffer.
169 * Since: 2.24
171 g_object_class_install_property (gobject_class,
172 PROP_SIZE,
173 g_param_spec_ulong ("size",
174 P_("Data Buffer Size"),
175 P_("Current size of the data buffer."),
176 0, G_MAXULONG, 0,
177 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
178 G_PARAM_STATIC_STRINGS));
181 * GMemoryOutputStream:data-size:
183 * Size of data written to the buffer.
185 * Since: 2.24
187 g_object_class_install_property (gobject_class,
188 PROP_DATA_SIZE,
189 g_param_spec_ulong ("data-size",
190 P_("Data Size"),
191 P_("Size of data written to the buffer."),
192 0, G_MAXULONG, 0,
193 G_PARAM_READABLE |
194 G_PARAM_STATIC_STRINGS));
197 * GMemoryOutputStream:realloc-function: (skip)
199 * Function with realloc semantics called to enlarge the buffer.
201 * Since: 2.24
203 g_object_class_install_property (gobject_class,
204 PROP_REALLOC_FUNCTION,
205 g_param_spec_pointer ("realloc-function",
206 P_("Memory Reallocation Function"),
207 P_("Function with realloc semantics called to enlarge the buffer."),
208 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
209 G_PARAM_STATIC_STRINGS));
212 * GMemoryOutputStream:destroy-function: (skip)
214 * Function called with the buffer as argument when the stream is destroyed.
216 * Since: 2.24
218 g_object_class_install_property (gobject_class,
219 PROP_DESTROY_FUNCTION,
220 g_param_spec_pointer ("destroy-function",
221 P_("Destroy Notification Function"),
222 P_("Function called with the buffer as argument when the stream is destroyed."),
223 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
224 G_PARAM_STATIC_STRINGS));
227 static void
228 g_memory_output_stream_set_property (GObject *object,
229 guint prop_id,
230 const GValue *value,
231 GParamSpec *pspec)
233 GMemoryOutputStream *stream;
234 GMemoryOutputStreamPrivate *priv;
236 stream = G_MEMORY_OUTPUT_STREAM (object);
237 priv = stream->priv;
239 switch (prop_id)
241 case PROP_DATA:
242 priv->data = g_value_get_pointer (value);
243 break;
244 case PROP_SIZE:
245 priv->len = g_value_get_ulong (value);
246 break;
247 case PROP_REALLOC_FUNCTION:
248 priv->realloc_fn = g_value_get_pointer (value);
249 break;
250 case PROP_DESTROY_FUNCTION:
251 priv->destroy = g_value_get_pointer (value);
252 break;
253 default:
254 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
255 break;
259 static void
260 g_memory_output_stream_get_property (GObject *object,
261 guint prop_id,
262 GValue *value,
263 GParamSpec *pspec)
265 GMemoryOutputStream *stream;
266 GMemoryOutputStreamPrivate *priv;
268 stream = G_MEMORY_OUTPUT_STREAM (object);
269 priv = stream->priv;
271 switch (prop_id)
273 case PROP_DATA:
274 g_value_set_pointer (value, priv->data);
275 break;
276 case PROP_SIZE:
277 g_value_set_ulong (value, priv->len);
278 break;
279 case PROP_DATA_SIZE:
280 g_value_set_ulong (value, priv->valid_len);
281 break;
282 case PROP_REALLOC_FUNCTION:
283 g_value_set_pointer (value, priv->realloc_fn);
284 break;
285 case PROP_DESTROY_FUNCTION:
286 g_value_set_pointer (value, priv->destroy);
287 break;
288 default:
289 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
290 break;
294 static void
295 g_memory_output_stream_finalize (GObject *object)
297 GMemoryOutputStream *stream;
298 GMemoryOutputStreamPrivate *priv;
300 stream = G_MEMORY_OUTPUT_STREAM (object);
301 priv = stream->priv;
303 if (priv->destroy)
304 priv->destroy (priv->data);
306 G_OBJECT_CLASS (g_memory_output_stream_parent_class)->finalize (object);
309 static void
310 g_memory_output_stream_seekable_iface_init (GSeekableIface *iface)
312 iface->tell = g_memory_output_stream_tell;
313 iface->can_seek = g_memory_output_stream_can_seek;
314 iface->seek = g_memory_output_stream_seek;
315 iface->can_truncate = g_memory_output_stream_can_truncate;
316 iface->truncate_fn = g_memory_output_stream_truncate;
320 static void
321 g_memory_output_stream_init (GMemoryOutputStream *stream)
323 stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (stream,
324 G_TYPE_MEMORY_OUTPUT_STREAM,
325 GMemoryOutputStreamPrivate);
326 stream->priv->pos = 0;
327 stream->priv->valid_len = 0;
331 * g_memory_output_stream_new: (skip)
332 * @data: pointer to a chunk of memory to use, or %NULL
333 * @size: the size of @data
334 * @realloc_function: a function with realloc() semantics (like g_realloc())
335 * to be called when @data needs to be grown, or %NULL
336 * @destroy_function: a function to be called on @data when the stream is
337 * finalized, or %NULL
339 * Creates a new #GMemoryOutputStream.
341 * If @data is non-%NULL, the stream will use that for its internal storage.
342 * If @realloc_fn is non-%NULL, it will be used for resizing the internal
343 * storage when necessary. To construct a fixed-size output stream,
344 * pass %NULL as @realloc_fn.
346 * |[
347 * /&ast; a stream that can grow &ast;/
348 * stream = g_memory_output_stream_new (NULL, 0, realloc, free);
350 * /&ast; another stream that can grow &ast;/
351 * stream2 = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
353 * /&ast; a fixed-size stream &ast;/
354 * data = malloc (200);
355 * stream3 = g_memory_output_stream_new (data, 200, NULL, free);
356 * ]|
358 * Return value: A newly created #GMemoryOutputStream object.
360 GOutputStream *
361 g_memory_output_stream_new (gpointer data,
362 gsize size,
363 GReallocFunc realloc_function,
364 GDestroyNotify destroy_function)
366 GOutputStream *stream;
368 stream = g_object_new (G_TYPE_MEMORY_OUTPUT_STREAM,
369 "data", data,
370 "size", size,
371 "realloc-function", realloc_function,
372 "destroy-function", destroy_function,
373 NULL);
375 return stream;
379 * g_memory_output_stream_get_data:
380 * @ostream: a #GMemoryOutputStream
382 * Gets any loaded data from the @ostream.
384 * Note that the returned pointer may become invalid on the next
385 * write or truncate operation on the stream.
387 * Returns: (transfer none): pointer to the stream's data
389 gpointer
390 g_memory_output_stream_get_data (GMemoryOutputStream *ostream)
392 g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
394 return ostream->priv->data;
398 * g_memory_output_stream_get_size:
399 * @ostream: a #GMemoryOutputStream
401 * Gets the size of the currently allocated data area (available from
402 * g_memory_output_stream_get_data()). If the stream isn't
403 * growable (no realloc was passed to g_memory_output_stream_new()) then
404 * this is the maximum size of the stream and further writes
405 * will return %G_IO_ERROR_NO_SPACE.
407 * Note that for growable streams the returned size may become invalid on
408 * the next write or truncate operation on the stream.
410 * If you want the number of bytes currently written to the stream, use
411 * g_memory_output_stream_get_data_size().
413 * Returns: the number of bytes allocated for the data buffer
415 gsize
416 g_memory_output_stream_get_size (GMemoryOutputStream *ostream)
418 g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
420 return ostream->priv->len;
424 * g_memory_output_stream_get_data_size:
425 * @ostream: a #GMemoryOutputStream
427 * Returns the number of bytes from the start up
428 * to including the last byte written in the stream
429 * that has not been truncated away.
431 * Returns: the number of bytes written to the stream
433 * Since: 2.18
435 gsize
436 g_memory_output_stream_get_data_size (GMemoryOutputStream *ostream)
438 g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
440 return ostream->priv->valid_len;
444 * g_memory_output_stream_steal_data:
445 * @ostream: a #GMemoryOutputStream
447 * Gets any loaded data from the @ostream. Ownership of the data
448 * is transferred to the caller; when no longer needed it must be
449 * freed using the free function set in @ostream's
450 * #GMemoryOutputStream:destroy-function property.
452 * @ostream must be closed before calling this function.
454 * Returns: (transfer full): the stream's data
456 * Since: 2.26
458 gpointer
459 g_memory_output_stream_steal_data (GMemoryOutputStream *ostream)
461 gpointer data;
463 g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
464 g_return_val_if_fail (g_output_stream_is_closed (G_OUTPUT_STREAM (ostream)), NULL);
466 data = ostream->priv->data;
467 ostream->priv->data = NULL;
469 return data;
472 static gboolean
473 array_resize (GMemoryOutputStream *ostream,
474 gsize size,
475 gboolean allow_partial,
476 GError **error)
478 GMemoryOutputStreamPrivate *priv;
479 gpointer data;
480 gsize len;
482 priv = ostream->priv;
484 if (priv->len == size)
485 return TRUE;
487 if (!priv->realloc_fn)
489 if (allow_partial &&
490 priv->pos < priv->len)
491 return TRUE; /* Short write */
493 g_set_error_literal (error,
494 G_IO_ERROR,
495 G_IO_ERROR_NO_SPACE,
496 _("Memory output stream not resizable"));
497 return FALSE;
500 len = priv->len;
501 data = priv->realloc_fn (priv->data, size);
503 if (size > 0 && !data)
505 if (allow_partial &&
506 priv->pos < priv->len)
507 return TRUE; /* Short write */
509 g_set_error_literal (error,
510 G_IO_ERROR,
511 G_IO_ERROR_NO_SPACE,
512 _("Failed to resize memory output stream"));
513 return FALSE;
516 if (size > len)
517 memset ((guint8 *)data + len, 0, size - len);
519 priv->data = data;
520 priv->len = size;
522 if (priv->len < priv->valid_len)
523 priv->valid_len = priv->len;
525 return TRUE;
528 static gint
529 g_nearest_pow (gint num)
531 gint n = 1;
533 while (n < num)
534 n <<= 1;
536 return n;
539 static gssize
540 g_memory_output_stream_write (GOutputStream *stream,
541 const void *buffer,
542 gsize count,
543 GCancellable *cancellable,
544 GError **error)
546 GMemoryOutputStream *ostream;
547 GMemoryOutputStreamPrivate *priv;
548 guint8 *dest;
549 gsize new_size;
551 ostream = G_MEMORY_OUTPUT_STREAM (stream);
552 priv = ostream->priv;
554 if (count == 0)
555 return 0;
557 /* Check for address space overflow, but only if the buffer is resizable.
558 Otherwise we just do a short write and don't worry. */
559 if (priv->realloc_fn && priv->pos + count < priv->pos)
560 goto overflow;
562 if (priv->pos + count > priv->len)
564 /* At least enought to fit the write, rounded up
565 for greater than linear growth.
566 TODO: This wastes a lot of memory at large stream sizes.
567 Figure out a more rational allocation strategy. */
568 new_size = g_nearest_pow (priv->pos + count);
569 /* Check for overflow again. We have only checked if
570 pos + count > G_MAXSIZE, but it only catches the case of writing
571 more than 4GiB total on a 32-bit system. There's still the problem
572 of g_nearest_pow overflowing above 0x7fffffff, so we're
573 effectively limited to 2GiB. */
574 if (new_size < priv->len)
575 goto overflow;
577 new_size = MAX (new_size, MIN_ARRAY_SIZE);
578 if (!array_resize (ostream, new_size, TRUE, error))
579 return -1;
582 /* Make sure we handle short writes if the array_resize
583 only added part of the required memory */
584 count = MIN (count, priv->len - priv->pos);
586 dest = (guint8 *)priv->data + priv->pos;
587 memcpy (dest, buffer, count);
588 priv->pos += count;
590 if (priv->pos > priv->valid_len)
591 priv->valid_len = priv->pos;
593 return count;
595 overflow:
596 /* Overflow: buffer size would need to be bigger than G_MAXSIZE. */
597 g_set_error_literal (error,
598 G_IO_ERROR,
599 G_IO_ERROR_NO_SPACE,
600 _("Amount of memory required to process the write is "
601 "larger than available address space"));
602 return -1;
605 static gboolean
606 g_memory_output_stream_close (GOutputStream *stream,
607 GCancellable *cancellable,
608 GError **error)
610 return TRUE;
613 static void
614 g_memory_output_stream_write_async (GOutputStream *stream,
615 const void *buffer,
616 gsize count,
617 int io_priority,
618 GCancellable *cancellable,
619 GAsyncReadyCallback callback,
620 gpointer data)
622 GSimpleAsyncResult *simple;
623 gssize nwritten;
625 nwritten = g_memory_output_stream_write (stream,
626 buffer,
627 count,
628 cancellable,
629 NULL);
631 simple = g_simple_async_result_new (G_OBJECT (stream),
632 callback,
633 data,
634 g_memory_output_stream_write_async);
636 g_simple_async_result_set_op_res_gssize (simple, nwritten);
637 g_simple_async_result_complete_in_idle (simple);
638 g_object_unref (simple);
641 static gssize
642 g_memory_output_stream_write_finish (GOutputStream *stream,
643 GAsyncResult *result,
644 GError **error)
646 GSimpleAsyncResult *simple;
647 gssize nwritten;
649 simple = G_SIMPLE_ASYNC_RESULT (result);
651 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) ==
652 g_memory_output_stream_write_async);
654 nwritten = g_simple_async_result_get_op_res_gssize (simple);
656 return nwritten;
659 static void
660 g_memory_output_stream_close_async (GOutputStream *stream,
661 int io_priority,
662 GCancellable *cancellable,
663 GAsyncReadyCallback callback,
664 gpointer data)
666 GSimpleAsyncResult *simple;
668 simple = g_simple_async_result_new (G_OBJECT (stream),
669 callback,
670 data,
671 g_memory_output_stream_close_async);
674 /* will always return TRUE */
675 g_memory_output_stream_close (stream, cancellable, NULL);
677 g_simple_async_result_complete_in_idle (simple);
678 g_object_unref (simple);
681 static gboolean
682 g_memory_output_stream_close_finish (GOutputStream *stream,
683 GAsyncResult *result,
684 GError **error)
686 GSimpleAsyncResult *simple;
688 simple = G_SIMPLE_ASYNC_RESULT (result);
690 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) ==
691 g_memory_output_stream_close_async);
693 return TRUE;
696 static goffset
697 g_memory_output_stream_tell (GSeekable *seekable)
699 GMemoryOutputStream *stream;
700 GMemoryOutputStreamPrivate *priv;
702 stream = G_MEMORY_OUTPUT_STREAM (seekable);
703 priv = stream->priv;
705 return priv->pos;
708 static gboolean
709 g_memory_output_stream_can_seek (GSeekable *seekable)
711 return TRUE;
714 static gboolean
715 g_memory_output_stream_seek (GSeekable *seekable,
716 goffset offset,
717 GSeekType type,
718 GCancellable *cancellable,
719 GError **error)
721 GMemoryOutputStream *stream;
722 GMemoryOutputStreamPrivate *priv;
723 goffset absolute;
725 stream = G_MEMORY_OUTPUT_STREAM (seekable);
726 priv = stream->priv;
728 switch (type)
730 case G_SEEK_CUR:
731 absolute = priv->pos + offset;
732 break;
734 case G_SEEK_SET:
735 absolute = offset;
736 break;
738 case G_SEEK_END:
739 absolute = priv->len + offset;
740 break;
742 default:
743 g_set_error_literal (error,
744 G_IO_ERROR,
745 G_IO_ERROR_INVALID_ARGUMENT,
746 _("Invalid GSeekType supplied"));
748 return FALSE;
751 if (absolute < 0)
753 g_set_error_literal (error,
754 G_IO_ERROR,
755 G_IO_ERROR_INVALID_ARGUMENT,
756 _("Requested seek before the beginning of the stream"));
757 return FALSE;
760 if (absolute > priv->len)
762 g_set_error_literal (error,
763 G_IO_ERROR,
764 G_IO_ERROR_INVALID_ARGUMENT,
765 _("Requested seek beyond the end of the stream"));
766 return FALSE;
769 priv->pos = absolute;
771 return TRUE;
774 static gboolean
775 g_memory_output_stream_can_truncate (GSeekable *seekable)
777 GMemoryOutputStream *ostream;
778 GMemoryOutputStreamPrivate *priv;
780 ostream = G_MEMORY_OUTPUT_STREAM (seekable);
781 priv = ostream->priv;
783 return priv->realloc_fn != NULL;
786 static gboolean
787 g_memory_output_stream_truncate (GSeekable *seekable,
788 goffset offset,
789 GCancellable *cancellable,
790 GError **error)
792 GMemoryOutputStream *ostream = G_MEMORY_OUTPUT_STREAM (seekable);
794 if (!array_resize (ostream, offset, FALSE, error))
795 return FALSE;
797 return TRUE;