gio: implement GPollableInput/OutputStream in more stream types
[platform/upstream/glib.git] / gio / gmemoryoutputstream.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  *
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.
9  *
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.
14  *
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.
19  *
20  * Authors:
21  *   Christian Kellner <gicmo@gnome.org>
22  *   Krzysztof KosiƄski <tweenk.pl@gmail.com>
23  */
24
25 #include "config.h"
26 #include "gmemoryoutputstream.h"
27 #include "goutputstream.h"
28 #include "gpollableoutputstream.h"
29 #include "gseekable.h"
30 #include "gsimpleasyncresult.h"
31 #include "gioerror.h"
32 #include "string.h"
33 #include "glibintl.h"
34
35
36 /**
37  * SECTION:gmemoryoutputstream
38  * @short_description: Streaming output operations on memory chunks
39  * @include: gio/gio.h
40  * @see_also: #GMemoryInputStream
41  *
42  * #GMemoryOutputStream is a class for using arbitrary
43  * memory chunks as output for GIO streaming output operations.
44  *
45  * As of GLib 2.34, #GMemoryOutputStream implements
46  * #GPollableOutputStream.
47  */
48
49 #define MIN_ARRAY_SIZE  16
50
51 enum {
52   PROP_0,
53   PROP_DATA,
54   PROP_SIZE,
55   PROP_DATA_SIZE,
56   PROP_REALLOC_FUNCTION,
57   PROP_DESTROY_FUNCTION
58 };
59
60 struct _GMemoryOutputStreamPrivate {
61   
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. */
67
68   GReallocFunc   realloc_fn;
69   GDestroyNotify destroy;
70 };
71
72 static void     g_memory_output_stream_set_property (GObject      *object,
73                                                      guint         prop_id,
74                                                      const GValue *value,
75                                                      GParamSpec   *pspec);
76 static void     g_memory_output_stream_get_property (GObject      *object,
77                                                      guint         prop_id,
78                                                      GValue       *value,
79                                                      GParamSpec   *pspec);
80 static void     g_memory_output_stream_finalize     (GObject      *object);
81
82 static gssize   g_memory_output_stream_write       (GOutputStream *stream,
83                                                     const void    *buffer,
84                                                     gsize          count,
85                                                     GCancellable  *cancellable,
86                                                     GError       **error);
87
88 static gboolean g_memory_output_stream_close       (GOutputStream  *stream,
89                                                     GCancellable   *cancellable,
90                                                     GError        **error);
91
92 static void     g_memory_output_stream_write_async  (GOutputStream        *stream,
93                                                      const void           *buffer,
94                                                      gsize                 count,
95                                                      int                   io_priority,
96                                                      GCancellable         *cancellable,
97                                                      GAsyncReadyCallback   callback,
98                                                      gpointer              data);
99 static gssize   g_memory_output_stream_write_finish (GOutputStream        *stream,
100                                                      GAsyncResult         *result,
101                                                      GError              **error);
102 static void     g_memory_output_stream_close_async  (GOutputStream        *stream,
103                                                      int                   io_priority,
104                                                      GCancellable         *cancellable,
105                                                      GAsyncReadyCallback   callback,
106                                                      gpointer              data);
107 static gboolean g_memory_output_stream_close_finish (GOutputStream        *stream,
108                                                      GAsyncResult         *result,
109                                                      GError              **error);
110
111 static void     g_memory_output_stream_seekable_iface_init (GSeekableIface  *iface);
112 static goffset  g_memory_output_stream_tell                (GSeekable       *seekable);
113 static gboolean g_memory_output_stream_can_seek            (GSeekable       *seekable);
114 static gboolean g_memory_output_stream_seek                (GSeekable       *seekable,
115                                                            goffset          offset,
116                                                            GSeekType        type,
117                                                            GCancellable    *cancellable,
118                                                            GError         **error);
119 static gboolean g_memory_output_stream_can_truncate        (GSeekable       *seekable);
120 static gboolean g_memory_output_stream_truncate            (GSeekable       *seekable,
121                                                            goffset          offset,
122                                                            GCancellable    *cancellable,
123                                                            GError         **error);
124
125 static gboolean g_memory_output_stream_is_writable       (GPollableOutputStream *stream);
126 static GSource *g_memory_output_stream_create_source     (GPollableOutputStream *stream,
127                                                           GCancellable          *cancellable);
128
129 static void g_memory_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface);
130
131 G_DEFINE_TYPE_WITH_CODE (GMemoryOutputStream, g_memory_output_stream, G_TYPE_OUTPUT_STREAM,
132                          G_IMPLEMENT_INTERFACE (G_TYPE_SEEKABLE,
133                                                 g_memory_output_stream_seekable_iface_init);
134                          G_IMPLEMENT_INTERFACE (G_TYPE_POLLABLE_OUTPUT_STREAM,
135                                                 g_memory_output_stream_pollable_iface_init))
136
137
138 static void
139 g_memory_output_stream_class_init (GMemoryOutputStreamClass *klass)
140 {
141   GOutputStreamClass *ostream_class;
142   GObjectClass *gobject_class;
143
144   g_type_class_add_private (klass, sizeof (GMemoryOutputStreamPrivate));
145
146   gobject_class = G_OBJECT_CLASS (klass);
147   gobject_class->set_property = g_memory_output_stream_set_property;
148   gobject_class->get_property = g_memory_output_stream_get_property;
149   gobject_class->finalize     = g_memory_output_stream_finalize;
150
151   ostream_class = G_OUTPUT_STREAM_CLASS (klass);
152
153   ostream_class->write_fn = g_memory_output_stream_write;
154   ostream_class->close_fn = g_memory_output_stream_close;
155   ostream_class->write_async  = g_memory_output_stream_write_async;
156   ostream_class->write_finish = g_memory_output_stream_write_finish;
157   ostream_class->close_async  = g_memory_output_stream_close_async;
158   ostream_class->close_finish = g_memory_output_stream_close_finish;
159
160   /**
161    * GMemoryOutputStream:data:
162    *
163    * Pointer to buffer where data will be written.
164    *
165    * Since: 2.24
166    **/
167   g_object_class_install_property (gobject_class,
168                                    PROP_DATA,
169                                    g_param_spec_pointer ("data",
170                                                          P_("Data Buffer"),
171                                                          P_("Pointer to buffer where data will be written."),
172                                                          G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
173                                                          G_PARAM_STATIC_STRINGS));
174
175   /**
176    * GMemoryOutputStream:size:
177    *
178    * Current size of the data buffer.
179    *
180    * Since: 2.24
181    **/
182   g_object_class_install_property (gobject_class,
183                                    PROP_SIZE,
184                                    g_param_spec_ulong ("size",
185                                                        P_("Data Buffer Size"),
186                                                        P_("Current size of the data buffer."),
187                                                        0, G_MAXULONG, 0,
188                                                        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
189                                                        G_PARAM_STATIC_STRINGS));
190
191   /**
192    * GMemoryOutputStream:data-size:
193    *
194    * Size of data written to the buffer.
195    *
196    * Since: 2.24
197    **/
198   g_object_class_install_property (gobject_class,
199                                    PROP_DATA_SIZE,
200                                    g_param_spec_ulong ("data-size",
201                                                        P_("Data Size"),
202                                                        P_("Size of data written to the buffer."),
203                                                        0, G_MAXULONG, 0,
204                                                        G_PARAM_READABLE |
205                                                        G_PARAM_STATIC_STRINGS));
206
207   /**
208    * GMemoryOutputStream:realloc-function: (skip)
209    *
210    * Function with realloc semantics called to enlarge the buffer.
211    *
212    * Since: 2.24
213    **/
214   g_object_class_install_property (gobject_class,
215                                    PROP_REALLOC_FUNCTION,
216                                    g_param_spec_pointer ("realloc-function",
217                                                          P_("Memory Reallocation Function"),
218                                                          P_("Function with realloc semantics called to enlarge the buffer."),
219                                                          G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
220                                                          G_PARAM_STATIC_STRINGS));
221
222   /**
223    * GMemoryOutputStream:destroy-function: (skip)
224    *
225    * Function called with the buffer as argument when the stream is destroyed.
226    *
227    * Since: 2.24
228    **/
229   g_object_class_install_property (gobject_class,
230                                    PROP_DESTROY_FUNCTION,
231                                    g_param_spec_pointer ("destroy-function",
232                                                          P_("Destroy Notification Function"),
233                                                          P_("Function called with the buffer as argument when the stream is destroyed."),
234                                                          G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
235                                                          G_PARAM_STATIC_STRINGS));
236 }
237
238 static void
239 g_memory_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface)
240 {
241   iface->is_writable = g_memory_output_stream_is_writable;
242   iface->create_source = g_memory_output_stream_create_source;
243 }
244
245 static void
246 g_memory_output_stream_set_property (GObject      *object,
247                                      guint         prop_id,
248                                      const GValue *value,
249                                      GParamSpec   *pspec)
250 {
251   GMemoryOutputStream        *stream;
252   GMemoryOutputStreamPrivate *priv;
253
254   stream = G_MEMORY_OUTPUT_STREAM (object);
255   priv = stream->priv;
256
257   switch (prop_id)
258     {
259     case PROP_DATA:
260       priv->data = g_value_get_pointer (value);
261       break;
262     case PROP_SIZE:
263       priv->len = g_value_get_ulong (value);
264       break;
265     case PROP_REALLOC_FUNCTION:
266       priv->realloc_fn = g_value_get_pointer (value);
267       break;
268     case PROP_DESTROY_FUNCTION:
269       priv->destroy = g_value_get_pointer (value);
270       break;
271     default:
272       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
273       break;
274     }
275 }
276
277 static void
278 g_memory_output_stream_get_property (GObject      *object,
279                                      guint         prop_id,
280                                      GValue       *value,
281                                      GParamSpec   *pspec)
282 {
283   GMemoryOutputStream        *stream;
284   GMemoryOutputStreamPrivate *priv;
285
286   stream = G_MEMORY_OUTPUT_STREAM (object);
287   priv = stream->priv;
288
289   switch (prop_id)
290     {
291     case PROP_DATA:
292       g_value_set_pointer (value, priv->data);
293       break;
294     case PROP_SIZE:
295       g_value_set_ulong (value, priv->len);
296       break;
297     case PROP_DATA_SIZE:
298       g_value_set_ulong (value, priv->valid_len);
299       break;
300     case PROP_REALLOC_FUNCTION:
301       g_value_set_pointer (value, priv->realloc_fn);
302       break;
303     case PROP_DESTROY_FUNCTION:
304       g_value_set_pointer (value, priv->destroy);
305       break;
306     default:
307       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
308       break;
309     }
310 }
311
312 static void
313 g_memory_output_stream_finalize (GObject *object)
314 {
315   GMemoryOutputStream        *stream;
316   GMemoryOutputStreamPrivate *priv;
317
318   stream = G_MEMORY_OUTPUT_STREAM (object);
319   priv = stream->priv;
320   
321   if (priv->destroy)
322     priv->destroy (priv->data);
323
324   G_OBJECT_CLASS (g_memory_output_stream_parent_class)->finalize (object);
325 }
326
327 static void
328 g_memory_output_stream_seekable_iface_init (GSeekableIface *iface)
329 {
330   iface->tell         = g_memory_output_stream_tell;
331   iface->can_seek     = g_memory_output_stream_can_seek;
332   iface->seek         = g_memory_output_stream_seek;
333   iface->can_truncate = g_memory_output_stream_can_truncate;
334   iface->truncate_fn  = g_memory_output_stream_truncate;
335 }
336
337
338 static void
339 g_memory_output_stream_init (GMemoryOutputStream *stream)
340 {
341   stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (stream,
342                                               G_TYPE_MEMORY_OUTPUT_STREAM,
343                                               GMemoryOutputStreamPrivate);
344   stream->priv->pos = 0;
345   stream->priv->valid_len = 0;
346 }
347
348 /**
349  * g_memory_output_stream_new: (skip)
350  * @data: (allow-none): pointer to a chunk of memory to use, or %NULL
351  * @size: the size of @data
352  * @realloc_function: (allow-none): a function with realloc() semantics (like g_realloc())
353  *     to be called when @data needs to be grown, or %NULL
354  * @destroy_function: (allow-none): a function to be called on @data when the stream is
355  *     finalized, or %NULL
356  *
357  * Creates a new #GMemoryOutputStream.
358  *
359  * If @data is non-%NULL, the stream  will use that for its internal storage.
360  * If @realloc_fn is non-%NULL, it will be used for resizing the internal
361  * storage when necessary. To construct a fixed-size output stream,
362  * pass %NULL as @realloc_fn.
363  *
364  * |[
365  * /&ast; a stream that can grow &ast;/
366  * stream = g_memory_output_stream_new (NULL, 0, realloc, free);
367  *
368  * /&ast; another stream that can grow &ast;/
369  * stream2 = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
370  *
371  * /&ast; a fixed-size stream &ast;/
372  * data = malloc (200);
373  * stream3 = g_memory_output_stream_new (data, 200, NULL, free);
374  * ]|
375  *
376  * Return value: A newly created #GMemoryOutputStream object.
377  **/
378 GOutputStream *
379 g_memory_output_stream_new (gpointer       data,
380                             gsize          size,
381                             GReallocFunc   realloc_function,
382                             GDestroyNotify destroy_function)
383 {
384   GOutputStream *stream;
385
386   stream = g_object_new (G_TYPE_MEMORY_OUTPUT_STREAM,
387                          "data", data,
388                          "size", size,
389                          "realloc-function", realloc_function,
390                          "destroy-function", destroy_function,
391                          NULL);
392
393   return stream;
394 }
395
396 /**
397  * g_memory_output_stream_get_data:
398  * @ostream: a #GMemoryOutputStream
399  *
400  * Gets any loaded data from the @ostream.
401  *
402  * Note that the returned pointer may become invalid on the next
403  * write or truncate operation on the stream.
404  *
405  * Returns: (transfer none): pointer to the stream's data
406  **/
407 gpointer
408 g_memory_output_stream_get_data (GMemoryOutputStream *ostream)
409 {
410   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
411
412   return ostream->priv->data;
413 }
414
415 /**
416  * g_memory_output_stream_get_size:
417  * @ostream: a #GMemoryOutputStream
418  *
419  * Gets the size of the currently allocated data area (available from
420  * g_memory_output_stream_get_data()). If the stream isn't
421  * growable (no realloc was passed to g_memory_output_stream_new()) then
422  * this is the maximum size of the stream and further writes
423  * will return %G_IO_ERROR_NO_SPACE.
424  *
425  * Note that for growable streams the returned size may become invalid on
426  * the next write or truncate operation on the stream.
427  *
428  * If you want the number of bytes currently written to the stream, use
429  * g_memory_output_stream_get_data_size().
430  *
431  * Returns: the number of bytes allocated for the data buffer
432  */
433 gsize
434 g_memory_output_stream_get_size (GMemoryOutputStream *ostream)
435 {
436   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
437
438   return ostream->priv->len;
439 }
440
441 /**
442  * g_memory_output_stream_get_data_size:
443  * @ostream: a #GMemoryOutputStream
444  *
445  * Returns the number of bytes from the start up
446  * to including the last byte written in the stream
447  * that has not been truncated away.
448  *
449  * Returns: the number of bytes written to the stream
450  *
451  * Since: 2.18
452  */
453 gsize
454 g_memory_output_stream_get_data_size (GMemoryOutputStream *ostream)
455 {
456   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
457
458   return ostream->priv->valid_len;
459 }
460
461 /**
462  * g_memory_output_stream_steal_data:
463  * @ostream: a #GMemoryOutputStream
464  *
465  * Gets any loaded data from the @ostream. Ownership of the data
466  * is transferred to the caller; when no longer needed it must be
467  * freed using the free function set in @ostream's
468  * #GMemoryOutputStream:destroy-function property.
469  *
470  * @ostream must be closed before calling this function.
471  *
472  * Returns: (transfer full): the stream's data
473  *
474  * Since: 2.26
475  **/
476 gpointer
477 g_memory_output_stream_steal_data (GMemoryOutputStream *ostream)
478 {
479   gpointer data;
480
481   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
482   g_return_val_if_fail (g_output_stream_is_closed (G_OUTPUT_STREAM (ostream)), NULL);
483
484   data = ostream->priv->data;
485   ostream->priv->data = NULL;
486
487   return data;
488 }
489
490 static gboolean
491 array_resize (GMemoryOutputStream  *ostream,
492               gsize                 size,
493               gboolean              allow_partial,
494               GError              **error)
495 {
496   GMemoryOutputStreamPrivate *priv;
497   gpointer data;
498   gsize len;
499
500   priv = ostream->priv;
501
502   if (priv->len == size)
503     return TRUE;
504
505   if (!priv->realloc_fn)
506     {
507       if (allow_partial &&
508           priv->pos < priv->len)
509         return TRUE; /* Short write */
510
511       g_set_error_literal (error,
512                            G_IO_ERROR,
513                            G_IO_ERROR_NO_SPACE,
514                            _("Memory output stream not resizable"));
515       return FALSE;
516     }
517
518   len = priv->len;
519   data = priv->realloc_fn (priv->data, size);
520
521   if (size > 0 && !data)
522     {
523       if (allow_partial &&
524           priv->pos < priv->len)
525         return TRUE; /* Short write */
526
527       g_set_error_literal (error,
528                            G_IO_ERROR,
529                            G_IO_ERROR_NO_SPACE,
530                            _("Failed to resize memory output stream"));
531       return FALSE;
532     }
533
534   if (size > len)
535     memset ((guint8 *)data + len, 0, size - len);
536
537   priv->data = data;
538   priv->len = size;
539
540   if (priv->len < priv->valid_len)
541     priv->valid_len = priv->len;
542
543   return TRUE;
544 }
545
546 static gint
547 g_nearest_pow (gint num)
548 {
549   gint n = 1;
550
551   while (n < num)
552     n <<= 1;
553
554   return n;
555 }
556
557 static gssize
558 g_memory_output_stream_write (GOutputStream  *stream,
559                               const void     *buffer,
560                               gsize           count,
561                               GCancellable   *cancellable,
562                               GError        **error)
563 {
564   GMemoryOutputStream        *ostream;
565   GMemoryOutputStreamPrivate *priv;
566   guint8   *dest;
567   gsize new_size;
568
569   ostream = G_MEMORY_OUTPUT_STREAM (stream);
570   priv = ostream->priv;
571
572   if (count == 0)
573     return 0;
574
575   /* Check for address space overflow, but only if the buffer is resizable.
576      Otherwise we just do a short write and don't worry. */
577   if (priv->realloc_fn && priv->pos + count < priv->pos)
578     goto overflow;
579
580   if (priv->pos + count > priv->len)
581     {
582       /* At least enought to fit the write, rounded up
583              for greater than linear growth.
584          TODO: This wastes a lot of memory at large stream sizes.
585                Figure out a more rational allocation strategy. */
586       new_size = g_nearest_pow (priv->pos + count);
587       /* Check for overflow again. We have only checked if
588          pos + count > G_MAXSIZE, but it only catches the case of writing
589          more than 4GiB total on a 32-bit system. There's still the problem
590          of g_nearest_pow overflowing above 0x7fffffff, so we're
591          effectively limited to 2GiB. */
592       if (new_size < priv->len)
593         goto overflow;
594
595       new_size = MAX (new_size, MIN_ARRAY_SIZE);
596       if (!array_resize (ostream, new_size, TRUE, error))
597         return -1;
598     }
599
600   /* Make sure we handle short writes if the array_resize
601      only added part of the required memory */
602   count = MIN (count, priv->len - priv->pos);
603
604   dest = (guint8 *)priv->data + priv->pos;
605   memcpy (dest, buffer, count);
606   priv->pos += count;
607
608   if (priv->pos > priv->valid_len)
609     priv->valid_len = priv->pos;
610
611   return count;
612
613  overflow:
614   /* Overflow: buffer size would need to be bigger than G_MAXSIZE. */
615   g_set_error_literal (error,
616                        G_IO_ERROR,
617                        G_IO_ERROR_NO_SPACE,
618                        _("Amount of memory required to process the write is "
619                          "larger than available address space"));
620   return -1;
621 }
622
623 static gboolean
624 g_memory_output_stream_close (GOutputStream  *stream,
625                               GCancellable   *cancellable,
626                               GError        **error)
627 {
628   return TRUE;
629 }
630
631 static void
632 g_memory_output_stream_write_async (GOutputStream       *stream,
633                                     const void          *buffer,
634                                     gsize                count,
635                                     int                  io_priority,
636                                     GCancellable        *cancellable,
637                                     GAsyncReadyCallback  callback,
638                                     gpointer             data)
639 {
640   GSimpleAsyncResult *simple;
641   GError *error = NULL;
642   gssize nwritten;
643
644   nwritten = G_OUTPUT_STREAM_GET_CLASS (stream)->write_fn (stream,
645                                                            buffer,
646                                                            count,
647                                                            cancellable,
648                                                            &error);
649
650   simple = g_simple_async_result_new (G_OBJECT (stream),
651                                       callback,
652                                       data,
653                                       g_memory_output_stream_write_async);
654
655   if (error)
656     g_simple_async_result_take_error (simple, error);
657   else
658     g_simple_async_result_set_op_res_gssize (simple, nwritten);
659   g_simple_async_result_complete_in_idle (simple);
660   g_object_unref (simple);
661 }
662
663 static gssize
664 g_memory_output_stream_write_finish (GOutputStream  *stream,
665                                      GAsyncResult   *result,
666                                      GError        **error)
667 {
668   GSimpleAsyncResult *simple;
669   gssize nwritten;
670
671   simple = G_SIMPLE_ASYNC_RESULT (result);
672
673   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) ==
674                   g_memory_output_stream_write_async);
675
676   nwritten = g_simple_async_result_get_op_res_gssize (simple);
677
678   return nwritten;
679 }
680
681 static void
682 g_memory_output_stream_close_async (GOutputStream       *stream,
683                                     int                  io_priority,
684                                     GCancellable        *cancellable,
685                                     GAsyncReadyCallback  callback,
686                                     gpointer             data)
687 {
688   GSimpleAsyncResult *simple;
689
690   simple = g_simple_async_result_new (G_OBJECT (stream),
691                                       callback,
692                                       data,
693                                       g_memory_output_stream_close_async);
694
695
696   /* will always return TRUE */
697   g_memory_output_stream_close (stream, cancellable, NULL);
698
699   g_simple_async_result_complete_in_idle (simple);
700   g_object_unref (simple);
701 }
702
703 static gboolean
704 g_memory_output_stream_close_finish (GOutputStream  *stream,
705                                      GAsyncResult   *result,
706                                      GError        **error)
707 {
708   GSimpleAsyncResult *simple;
709
710   simple = G_SIMPLE_ASYNC_RESULT (result);
711
712   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) ==
713                   g_memory_output_stream_close_async);
714
715   return TRUE;
716 }
717
718 static goffset
719 g_memory_output_stream_tell (GSeekable *seekable)
720 {
721   GMemoryOutputStream *stream;
722   GMemoryOutputStreamPrivate *priv;
723
724   stream = G_MEMORY_OUTPUT_STREAM (seekable);
725   priv = stream->priv;
726
727   return priv->pos;
728 }
729
730 static gboolean
731 g_memory_output_stream_can_seek (GSeekable *seekable)
732 {
733   return TRUE;
734 }
735
736 static gboolean
737 g_memory_output_stream_seek (GSeekable    *seekable,
738                             goffset        offset,
739                             GSeekType      type,
740                             GCancellable  *cancellable,
741                             GError       **error)
742 {
743   GMemoryOutputStream        *stream;
744   GMemoryOutputStreamPrivate *priv;
745   goffset absolute;
746
747   stream = G_MEMORY_OUTPUT_STREAM (seekable);
748   priv = stream->priv;
749
750   switch (type)
751     {
752     case G_SEEK_CUR:
753       absolute = priv->pos + offset;
754       break;
755
756     case G_SEEK_SET:
757       absolute = offset;
758       break;
759
760     case G_SEEK_END:
761       absolute = priv->len + offset;
762       break;
763
764     default:
765       g_set_error_literal (error,
766                            G_IO_ERROR,
767                            G_IO_ERROR_INVALID_ARGUMENT,
768                            _("Invalid GSeekType supplied"));
769
770       return FALSE;
771     }
772
773   if (absolute < 0)
774     {
775       g_set_error_literal (error,
776                            G_IO_ERROR,
777                            G_IO_ERROR_INVALID_ARGUMENT,
778                            _("Requested seek before the beginning of the stream"));
779       return FALSE;
780     }
781
782   if (absolute > priv->len)
783     {
784       g_set_error_literal (error,
785                            G_IO_ERROR,
786                            G_IO_ERROR_INVALID_ARGUMENT,
787                            _("Requested seek beyond the end of the stream"));
788       return FALSE;
789     }
790
791   priv->pos = absolute;
792
793   return TRUE;
794 }
795
796 static gboolean
797 g_memory_output_stream_can_truncate (GSeekable *seekable)
798 {
799   GMemoryOutputStream *ostream;
800   GMemoryOutputStreamPrivate *priv;
801
802   ostream = G_MEMORY_OUTPUT_STREAM (seekable);
803   priv = ostream->priv;
804
805   return priv->realloc_fn != NULL;
806 }
807
808 static gboolean
809 g_memory_output_stream_truncate (GSeekable     *seekable,
810                                  goffset        offset,
811                                  GCancellable  *cancellable,
812                                  GError       **error)
813 {
814   GMemoryOutputStream *ostream = G_MEMORY_OUTPUT_STREAM (seekable);
815
816   if (!array_resize (ostream, offset, FALSE, error))
817     return FALSE;
818
819   return TRUE;
820 }
821
822 static gboolean
823 g_memory_output_stream_is_writable (GPollableOutputStream *stream)
824 {
825   return TRUE;
826 }
827
828 static GSource *
829 g_memory_output_stream_create_source (GPollableOutputStream *stream,
830                                       GCancellable          *cancellable)
831 {
832   GSource *base_source, *pollable_source;
833
834   base_source = g_timeout_source_new (0);
835   pollable_source = g_pollable_source_new_full (stream, base_source,
836                                                 cancellable);
837   g_source_unref (base_source);
838
839   return pollable_source;
840 }