gio: Update GMemoryOutputStream length after truncate
[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 "gtask.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 trivially implements
46  * #GPollableOutputStream: it always polls as ready.
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_close_async  (GOutputStream        *stream,
93                                                      int                   io_priority,
94                                                      GCancellable         *cancellable,
95                                                      GAsyncReadyCallback   callback,
96                                                      gpointer              data);
97 static gboolean g_memory_output_stream_close_finish (GOutputStream        *stream,
98                                                      GAsyncResult         *result,
99                                                      GError              **error);
100
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,
105                                                            goffset          offset,
106                                                            GSeekType        type,
107                                                            GCancellable    *cancellable,
108                                                            GError         **error);
109 static gboolean g_memory_output_stream_can_truncate        (GSeekable       *seekable);
110 static gboolean g_memory_output_stream_truncate            (GSeekable       *seekable,
111                                                            goffset          offset,
112                                                            GCancellable    *cancellable,
113                                                            GError         **error);
114
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);
118
119 static void g_memory_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface);
120
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))
127
128
129 static void
130 g_memory_output_stream_class_init (GMemoryOutputStreamClass *klass)
131 {
132   GOutputStreamClass *ostream_class;
133   GObjectClass *gobject_class;
134
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;
139
140   ostream_class = G_OUTPUT_STREAM_CLASS (klass);
141
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;
146
147   /**
148    * GMemoryOutputStream:data:
149    *
150    * Pointer to buffer where data will be written.
151    *
152    * Since: 2.24
153    **/
154   g_object_class_install_property (gobject_class,
155                                    PROP_DATA,
156                                    g_param_spec_pointer ("data",
157                                                          P_("Data Buffer"),
158                                                          P_("Pointer to buffer where data will be written."),
159                                                          G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
160                                                          G_PARAM_STATIC_STRINGS));
161
162   /**
163    * GMemoryOutputStream:size:
164    *
165    * Current size of the data buffer.
166    *
167    * Since: 2.24
168    **/
169   g_object_class_install_property (gobject_class,
170                                    PROP_SIZE,
171                                    g_param_spec_ulong ("size",
172                                                        P_("Data Buffer Size"),
173                                                        P_("Current size of the data buffer."),
174                                                        0, G_MAXULONG, 0,
175                                                        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
176                                                        G_PARAM_STATIC_STRINGS));
177
178   /**
179    * GMemoryOutputStream:data-size:
180    *
181    * Size of data written to the buffer.
182    *
183    * Since: 2.24
184    **/
185   g_object_class_install_property (gobject_class,
186                                    PROP_DATA_SIZE,
187                                    g_param_spec_ulong ("data-size",
188                                                        P_("Data Size"),
189                                                        P_("Size of data written to the buffer."),
190                                                        0, G_MAXULONG, 0,
191                                                        G_PARAM_READABLE |
192                                                        G_PARAM_STATIC_STRINGS));
193
194   /**
195    * GMemoryOutputStream:realloc-function: (skip)
196    *
197    * Function with realloc semantics called to enlarge the buffer.
198    *
199    * Since: 2.24
200    **/
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));
208
209   /**
210    * GMemoryOutputStream:destroy-function: (skip)
211    *
212    * Function called with the buffer as argument when the stream is destroyed.
213    *
214    * Since: 2.24
215    **/
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));
223 }
224
225 static void
226 g_memory_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface)
227 {
228   iface->is_writable = g_memory_output_stream_is_writable;
229   iface->create_source = g_memory_output_stream_create_source;
230 }
231
232 static void
233 g_memory_output_stream_set_property (GObject      *object,
234                                      guint         prop_id,
235                                      const GValue *value,
236                                      GParamSpec   *pspec)
237 {
238   GMemoryOutputStream        *stream;
239   GMemoryOutputStreamPrivate *priv;
240
241   stream = G_MEMORY_OUTPUT_STREAM (object);
242   priv = stream->priv;
243
244   switch (prop_id)
245     {
246     case PROP_DATA:
247       priv->data = g_value_get_pointer (value);
248       break;
249     case PROP_SIZE:
250       priv->len = g_value_get_ulong (value);
251       break;
252     case PROP_REALLOC_FUNCTION:
253       priv->realloc_fn = g_value_get_pointer (value);
254       break;
255     case PROP_DESTROY_FUNCTION:
256       priv->destroy = g_value_get_pointer (value);
257       break;
258     default:
259       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
260       break;
261     }
262 }
263
264 static void
265 g_memory_output_stream_get_property (GObject      *object,
266                                      guint         prop_id,
267                                      GValue       *value,
268                                      GParamSpec   *pspec)
269 {
270   GMemoryOutputStream        *stream;
271   GMemoryOutputStreamPrivate *priv;
272
273   stream = G_MEMORY_OUTPUT_STREAM (object);
274   priv = stream->priv;
275
276   switch (prop_id)
277     {
278     case PROP_DATA:
279       g_value_set_pointer (value, priv->data);
280       break;
281     case PROP_SIZE:
282       g_value_set_ulong (value, priv->len);
283       break;
284     case PROP_DATA_SIZE:
285       g_value_set_ulong (value, priv->valid_len);
286       break;
287     case PROP_REALLOC_FUNCTION:
288       g_value_set_pointer (value, priv->realloc_fn);
289       break;
290     case PROP_DESTROY_FUNCTION:
291       g_value_set_pointer (value, priv->destroy);
292       break;
293     default:
294       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
295       break;
296     }
297 }
298
299 static void
300 g_memory_output_stream_finalize (GObject *object)
301 {
302   GMemoryOutputStream        *stream;
303   GMemoryOutputStreamPrivate *priv;
304
305   stream = G_MEMORY_OUTPUT_STREAM (object);
306   priv = stream->priv;
307   
308   if (priv->destroy)
309     priv->destroy (priv->data);
310
311   G_OBJECT_CLASS (g_memory_output_stream_parent_class)->finalize (object);
312 }
313
314 static void
315 g_memory_output_stream_seekable_iface_init (GSeekableIface *iface)
316 {
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;
322 }
323
324
325 static void
326 g_memory_output_stream_init (GMemoryOutputStream *stream)
327 {
328   stream->priv = g_memory_output_stream_get_instance_private (stream);
329   stream->priv->pos = 0;
330   stream->priv->valid_len = 0;
331 }
332
333 /**
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
341  *
342  * Creates a new #GMemoryOutputStream.
343  *
344  * In most cases this is not the function you want.  See
345  * g_memory_output_stream_new_resizable() instead.
346  *
347  * If @data is non-%NULL, the stream will use that for its internal storage.
348  *
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.
356  *
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.
365  *
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).
371  *
372  * |[
373  * /&ast; a stream that can grow &ast;/
374  * stream = g_memory_output_stream_new (NULL, 0, realloc, free);
375  *
376  * /&ast; another stream that can grow &ast;/
377  * stream2 = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
378  *
379  * /&ast; a fixed-size stream &ast;/
380  * data = malloc (200);
381  * stream3 = g_memory_output_stream_new (data, 200, NULL, free);
382  * ]|
383  *
384  * Return value: A newly created #GMemoryOutputStream object.
385  **/
386 GOutputStream *
387 g_memory_output_stream_new (gpointer       data,
388                             gsize          size,
389                             GReallocFunc   realloc_function,
390                             GDestroyNotify destroy_function)
391 {
392   GOutputStream *stream;
393
394   stream = g_object_new (G_TYPE_MEMORY_OUTPUT_STREAM,
395                          "data", data,
396                          "size", size,
397                          "realloc-function", realloc_function,
398                          "destroy-function", destroy_function,
399                          NULL);
400
401   return stream;
402 }
403
404 /**
405  * g_memory_output_stream_new_resizable:
406  *
407  * Creates a new #GMemoryOutputStream, using g_realloc() and g_free()
408  * for memory allocation.
409  *
410  * Since: 2.36
411  */
412 GOutputStream *
413 g_memory_output_stream_new_resizable (void)
414 {
415   return g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
416 }
417
418 /**
419  * g_memory_output_stream_get_data:
420  * @ostream: a #GMemoryOutputStream
421  *
422  * Gets any loaded data from the @ostream.
423  *
424  * Note that the returned pointer may become invalid on the next
425  * write or truncate operation on the stream.
426  *
427  * Returns: (transfer none): pointer to the stream's data
428  **/
429 gpointer
430 g_memory_output_stream_get_data (GMemoryOutputStream *ostream)
431 {
432   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
433
434   return ostream->priv->data;
435 }
436
437 /**
438  * g_memory_output_stream_get_size:
439  * @ostream: a #GMemoryOutputStream
440  *
441  * Gets the size of the currently allocated data area (available from
442  * g_memory_output_stream_get_data()).
443  *
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
448  * stream.
449  *
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.
453  *
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().
456  *
457  * Returns: the number of bytes allocated for the data buffer
458  */
459 gsize
460 g_memory_output_stream_get_size (GMemoryOutputStream *ostream)
461 {
462   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
463
464   return ostream->priv->len;
465 }
466
467 /**
468  * g_memory_output_stream_get_data_size:
469  * @ostream: a #GMemoryOutputStream
470  *
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.
473  *
474  * Returns: the number of bytes written to the stream
475  *
476  * Since: 2.18
477  */
478 gsize
479 g_memory_output_stream_get_data_size (GMemoryOutputStream *ostream)
480 {
481   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
482
483   return ostream->priv->valid_len;
484 }
485
486 /**
487  * g_memory_output_stream_steal_data:
488  * @ostream: a #GMemoryOutputStream
489  *
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.
494  *
495  * @ostream must be closed before calling this function.
496  *
497  * Returns: (transfer full): the stream's data
498  *
499  * Since: 2.26
500  **/
501 gpointer
502 g_memory_output_stream_steal_data (GMemoryOutputStream *ostream)
503 {
504   gpointer data;
505
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);
508
509   data = ostream->priv->data;
510   ostream->priv->data = NULL;
511
512   return data;
513 }
514
515 /**
516  * g_memory_output_stream_steal_as_bytes:
517  * @ostream: a #GMemoryOutputStream
518  *
519  * Returns data from the @ostream as a #GBytes. @ostream must be
520  * closed before calling this function.
521  *
522  * Returns: (transfer full): the stream's data
523  *
524  * Since: 2.34
525  **/
526 GBytes *
527 g_memory_output_stream_steal_as_bytes (GMemoryOutputStream *ostream)
528 {
529   GBytes *result;
530
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);
533
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;
539
540   return result;
541 }
542
543 static gboolean
544 array_resize (GMemoryOutputStream  *ostream,
545               gsize                 size,
546               gboolean              allow_partial,
547               GError              **error)
548 {
549   GMemoryOutputStreamPrivate *priv;
550   gpointer data;
551   gsize len;
552
553   priv = ostream->priv;
554
555   if (priv->len == size)
556     return TRUE;
557
558   if (!priv->realloc_fn)
559     {
560       if (allow_partial &&
561           priv->pos < priv->len)
562         return TRUE; /* Short write */
563
564       g_set_error_literal (error,
565                            G_IO_ERROR,
566                            G_IO_ERROR_NO_SPACE,
567                            _("Memory output stream not resizable"));
568       return FALSE;
569     }
570
571   len = priv->len;
572   data = priv->realloc_fn (priv->data, size);
573
574   if (size > 0 && !data)
575     {
576       if (allow_partial &&
577           priv->pos < priv->len)
578         return TRUE; /* Short write */
579
580       g_set_error_literal (error,
581                            G_IO_ERROR,
582                            G_IO_ERROR_NO_SPACE,
583                            _("Failed to resize memory output stream"));
584       return FALSE;
585     }
586
587   if (size > len)
588     memset ((guint8 *)data + len, 0, size - len);
589
590   priv->data = data;
591   priv->len = size;
592
593   if (priv->len < priv->valid_len)
594     priv->valid_len = priv->len;
595
596   return TRUE;
597 }
598
599 static gint
600 g_nearest_pow (gint num)
601 {
602   gint n = 1;
603
604   while (n < num)
605     n <<= 1;
606
607   return n;
608 }
609
610 static gssize
611 g_memory_output_stream_write (GOutputStream  *stream,
612                               const void     *buffer,
613                               gsize           count,
614                               GCancellable   *cancellable,
615                               GError        **error)
616 {
617   GMemoryOutputStream        *ostream;
618   GMemoryOutputStreamPrivate *priv;
619   guint8   *dest;
620   gsize new_size;
621
622   ostream = G_MEMORY_OUTPUT_STREAM (stream);
623   priv = ostream->priv;
624
625   if (count == 0)
626     return 0;
627
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)
631     goto overflow;
632
633   if (priv->pos + count > priv->len)
634     {
635       /* At least enough to fit the write, rounded up for greater than
636        * linear growth.
637        *
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
641        * much memory.
642        */
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)
650         goto overflow;
651
652       new_size = MAX (new_size, MIN_ARRAY_SIZE);
653       if (!array_resize (ostream, new_size, TRUE, error))
654         return -1;
655     }
656
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);
660
661   dest = (guint8 *)priv->data + priv->pos;
662   memcpy (dest, buffer, count);
663   priv->pos += count;
664
665   if (priv->pos > priv->valid_len)
666     priv->valid_len = priv->pos;
667
668   return count;
669
670  overflow:
671   /* Overflow: buffer size would need to be bigger than G_MAXSIZE. */
672   g_set_error_literal (error,
673                        G_IO_ERROR,
674                        G_IO_ERROR_NO_SPACE,
675                        _("Amount of memory required to process the write is "
676                          "larger than available address space"));
677   return -1;
678 }
679
680 static gboolean
681 g_memory_output_stream_close (GOutputStream  *stream,
682                               GCancellable   *cancellable,
683                               GError        **error)
684 {
685   return TRUE;
686 }
687
688 static void
689 g_memory_output_stream_close_async (GOutputStream       *stream,
690                                     int                  io_priority,
691                                     GCancellable        *cancellable,
692                                     GAsyncReadyCallback  callback,
693                                     gpointer             data)
694 {
695   GTask *task;
696
697   task = g_task_new (stream, cancellable, callback, data);
698
699   /* will always return TRUE */
700   g_memory_output_stream_close (stream, cancellable, NULL);
701
702   g_task_return_boolean (task, TRUE);
703   g_object_unref (task);
704 }
705
706 static gboolean
707 g_memory_output_stream_close_finish (GOutputStream  *stream,
708                                      GAsyncResult   *result,
709                                      GError        **error)
710 {
711   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
712
713   return g_task_propagate_boolean (G_TASK (result), error);
714 }
715
716 static goffset
717 g_memory_output_stream_tell (GSeekable *seekable)
718 {
719   GMemoryOutputStream *stream;
720   GMemoryOutputStreamPrivate *priv;
721
722   stream = G_MEMORY_OUTPUT_STREAM (seekable);
723   priv = stream->priv;
724
725   return priv->pos;
726 }
727
728 static gboolean
729 g_memory_output_stream_can_seek (GSeekable *seekable)
730 {
731   return TRUE;
732 }
733
734 static gboolean
735 g_memory_output_stream_seek (GSeekable    *seekable,
736                              goffset        offset,
737                              GSeekType      type,
738                              GCancellable  *cancellable,
739                              GError       **error)
740 {
741   GMemoryOutputStream        *stream;
742   GMemoryOutputStreamPrivate *priv;
743   goffset absolute;
744
745   stream = G_MEMORY_OUTPUT_STREAM (seekable);
746   priv = stream->priv;
747
748   switch (type)
749     {
750     case G_SEEK_CUR:
751       absolute = priv->pos + offset;
752       break;
753
754     case G_SEEK_SET:
755       absolute = offset;
756       break;
757
758     case G_SEEK_END:
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.
762        */
763       if (priv->realloc_fn)
764         absolute = priv->valid_len + offset;
765       else
766         absolute = priv->len + offset;
767       break;
768
769     default:
770       g_set_error_literal (error,
771                            G_IO_ERROR,
772                            G_IO_ERROR_INVALID_ARGUMENT,
773                            _("Invalid GSeekType supplied"));
774
775       return FALSE;
776     }
777
778   if (absolute < 0)
779     {
780       g_set_error_literal (error,
781                            G_IO_ERROR,
782                            G_IO_ERROR_INVALID_ARGUMENT,
783                            _("Requested seek before the beginning of the stream"));
784       return FALSE;
785     }
786
787   /* Can't seek past the end of a fixed-size stream.
788    *
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.
792    * */
793   if (priv->realloc_fn == NULL && absolute > priv->len)
794     {
795       g_set_error_literal (error,
796                            G_IO_ERROR,
797                            G_IO_ERROR_INVALID_ARGUMENT,
798                            _("Requested seek beyond the end of the stream"));
799       return FALSE;
800     }
801
802   priv->pos = absolute;
803
804   return TRUE;
805 }
806
807 static gboolean
808 g_memory_output_stream_can_truncate (GSeekable *seekable)
809 {
810   GMemoryOutputStream *ostream;
811   GMemoryOutputStreamPrivate *priv;
812
813   ostream = G_MEMORY_OUTPUT_STREAM (seekable);
814   priv = ostream->priv;
815
816   /* We do not allow truncation of fixed-sized streams */
817   return priv->realloc_fn != NULL;
818 }
819
820 static gboolean
821 g_memory_output_stream_truncate (GSeekable     *seekable,
822                                  goffset        offset,
823                                  GCancellable  *cancellable,
824                                  GError       **error)
825 {
826   GMemoryOutputStream *ostream = G_MEMORY_OUTPUT_STREAM (seekable);
827
828   if (!array_resize (ostream, offset, FALSE, error))
829     return FALSE;
830
831   ostream->priv->valid_len = offset;
832
833   return TRUE;
834 }
835
836 static gboolean
837 g_memory_output_stream_is_writable (GPollableOutputStream *stream)
838 {
839   return TRUE;
840 }
841
842 static GSource *
843 g_memory_output_stream_create_source (GPollableOutputStream *stream,
844                                       GCancellable          *cancellable)
845 {
846   GSource *base_source, *pollable_source;
847
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);
851
852   return pollable_source;
853 }