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