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