Change semantics of seek on memory output stream
[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_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  * If @data is non-%NULL, the stream  will use that for its internal storage.
345  * If @realloc_fn is non-%NULL, it will be used for resizing the internal
346  * storage when necessary. To construct a fixed-size output stream,
347  * pass %NULL as @realloc_fn.
348  *
349  * |[
350  * /&ast; a stream that can grow &ast;/
351  * stream = g_memory_output_stream_new (NULL, 0, realloc, free);
352  *
353  * /&ast; another stream that can grow &ast;/
354  * stream2 = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
355  *
356  * /&ast; a fixed-size stream &ast;/
357  * data = malloc (200);
358  * stream3 = g_memory_output_stream_new (data, 200, NULL, free);
359  * ]|
360  *
361  * Return value: A newly created #GMemoryOutputStream object.
362  **/
363 GOutputStream *
364 g_memory_output_stream_new (gpointer       data,
365                             gsize          size,
366                             GReallocFunc   realloc_function,
367                             GDestroyNotify destroy_function)
368 {
369   GOutputStream *stream;
370
371   stream = g_object_new (G_TYPE_MEMORY_OUTPUT_STREAM,
372                          "data", data,
373                          "size", size,
374                          "realloc-function", realloc_function,
375                          "destroy-function", destroy_function,
376                          NULL);
377
378   return stream;
379 }
380
381 /**
382  * g_memory_output_stream_new_resizable:
383  *
384  * Creates a new #GMemoryOutputStream, using g_realloc() and g_free()
385  * for memory allocation.
386  *
387  * Since: 2.36
388  */
389 GOutputStream *
390 g_memory_output_stream_new_resizable (void)
391 {
392   return g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
393 }
394
395 /**
396  * g_memory_output_stream_get_data:
397  * @ostream: a #GMemoryOutputStream
398  *
399  * Gets any loaded data from the @ostream.
400  *
401  * Note that the returned pointer may become invalid on the next
402  * write or truncate operation on the stream.
403  *
404  * Returns: (transfer none): pointer to the stream's data
405  **/
406 gpointer
407 g_memory_output_stream_get_data (GMemoryOutputStream *ostream)
408 {
409   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
410
411   return ostream->priv->data;
412 }
413
414 /**
415  * g_memory_output_stream_get_size:
416  * @ostream: a #GMemoryOutputStream
417  *
418  * Gets the size of the currently allocated data area (available from
419  * g_memory_output_stream_get_data()). If the stream isn't
420  * growable (no realloc was passed to g_memory_output_stream_new()) then
421  * this is the maximum size of the stream and further writes
422  * will return %G_IO_ERROR_NO_SPACE.
423  *
424  * Note that for growable streams the returned size may become invalid on
425  * the next write or truncate operation on the stream.
426  *
427  * If you want the number of bytes currently written to the stream, use
428  * g_memory_output_stream_get_data_size().
429  *
430  * Returns: the number of bytes allocated for the data buffer
431  */
432 gsize
433 g_memory_output_stream_get_size (GMemoryOutputStream *ostream)
434 {
435   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
436
437   return ostream->priv->len;
438 }
439
440 /**
441  * g_memory_output_stream_get_data_size:
442  * @ostream: a #GMemoryOutputStream
443  *
444  * Returns the number of bytes from the start up
445  * to including the last byte written in the stream
446  * that has not been truncated away.
447  *
448  * Returns: the number of bytes written to the stream
449  *
450  * Since: 2.18
451  */
452 gsize
453 g_memory_output_stream_get_data_size (GMemoryOutputStream *ostream)
454 {
455   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
456
457   return ostream->priv->valid_len;
458 }
459
460 /**
461  * g_memory_output_stream_steal_data:
462  * @ostream: a #GMemoryOutputStream
463  *
464  * Gets any loaded data from the @ostream. Ownership of the data
465  * is transferred to the caller; when no longer needed it must be
466  * freed using the free function set in @ostream's
467  * #GMemoryOutputStream:destroy-function property.
468  *
469  * @ostream must be closed before calling this function.
470  *
471  * Returns: (transfer full): the stream's data
472  *
473  * Since: 2.26
474  **/
475 gpointer
476 g_memory_output_stream_steal_data (GMemoryOutputStream *ostream)
477 {
478   gpointer data;
479
480   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
481   g_return_val_if_fail (g_output_stream_is_closed (G_OUTPUT_STREAM (ostream)), NULL);
482
483   data = ostream->priv->data;
484   ostream->priv->data = NULL;
485
486   return data;
487 }
488
489 /**
490  * g_memory_output_stream_steal_as_bytes:
491  * @ostream: a #GMemoryOutputStream
492  *
493  * Returns data from the @ostream as a #GBytes. @ostream must be
494  * closed before calling this function.
495  *
496  * Returns: (transfer full): the stream's data
497  *
498  * Since: 2.34
499  **/
500 GBytes *
501 g_memory_output_stream_steal_as_bytes (GMemoryOutputStream *ostream)
502 {
503   GBytes *result;
504
505   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
506   g_return_val_if_fail (g_output_stream_is_closed (G_OUTPUT_STREAM (ostream)), NULL);
507
508   result = g_bytes_new_with_free_func (ostream->priv->data,
509                                        ostream->priv->valid_len,
510                                        ostream->priv->destroy,
511                                        ostream->priv->data);
512   ostream->priv->data = NULL;
513                              
514   return result;
515 }
516
517 static gboolean
518 array_resize (GMemoryOutputStream  *ostream,
519               gsize                 size,
520               gboolean              allow_partial,
521               GError              **error)
522 {
523   GMemoryOutputStreamPrivate *priv;
524   gpointer data;
525   gsize len;
526
527   priv = ostream->priv;
528
529   if (priv->len == size)
530     return TRUE;
531
532   if (!priv->realloc_fn)
533     {
534       if (allow_partial &&
535           priv->pos < priv->len)
536         return TRUE; /* Short write */
537
538       g_set_error_literal (error,
539                            G_IO_ERROR,
540                            G_IO_ERROR_NO_SPACE,
541                            _("Memory output stream not resizable"));
542       return FALSE;
543     }
544
545   len = priv->len;
546   data = priv->realloc_fn (priv->data, size);
547
548   if (size > 0 && !data)
549     {
550       if (allow_partial &&
551           priv->pos < priv->len)
552         return TRUE; /* Short write */
553
554       g_set_error_literal (error,
555                            G_IO_ERROR,
556                            G_IO_ERROR_NO_SPACE,
557                            _("Failed to resize memory output stream"));
558       return FALSE;
559     }
560
561   if (size > len)
562     memset ((guint8 *)data + len, 0, size - len);
563
564   priv->data = data;
565   priv->len = size;
566
567   if (priv->len < priv->valid_len)
568     priv->valid_len = priv->len;
569
570   return TRUE;
571 }
572
573 static gint
574 g_nearest_pow (gint num)
575 {
576   gint n = 1;
577
578   while (n < num)
579     n <<= 1;
580
581   return n;
582 }
583
584 static gssize
585 g_memory_output_stream_write (GOutputStream  *stream,
586                               const void     *buffer,
587                               gsize           count,
588                               GCancellable   *cancellable,
589                               GError        **error)
590 {
591   GMemoryOutputStream        *ostream;
592   GMemoryOutputStreamPrivate *priv;
593   guint8   *dest;
594   gsize new_size;
595
596   ostream = G_MEMORY_OUTPUT_STREAM (stream);
597   priv = ostream->priv;
598
599   if (count == 0)
600     return 0;
601
602   /* Check for address space overflow, but only if the buffer is resizable.
603      Otherwise we just do a short write and don't worry. */
604   if (priv->realloc_fn && priv->pos + count < priv->pos)
605     goto overflow;
606
607   if (priv->pos + count > priv->len)
608     {
609       /* At least enought to fit the write, rounded up
610              for greater than linear growth.
611          TODO: This wastes a lot of memory at large stream sizes.
612                Figure out a more rational allocation strategy. */
613       new_size = g_nearest_pow (priv->pos + count);
614       /* Check for overflow again. We have only checked if
615          pos + count > G_MAXSIZE, but it only catches the case of writing
616          more than 4GiB total on a 32-bit system. There's still the problem
617          of g_nearest_pow overflowing above 0x7fffffff, so we're
618          effectively limited to 2GiB. */
619       if (new_size < priv->len)
620         goto overflow;
621
622       new_size = MAX (new_size, MIN_ARRAY_SIZE);
623       if (!array_resize (ostream, new_size, TRUE, error))
624         return -1;
625     }
626
627   /* Make sure we handle short writes if the array_resize
628      only added part of the required memory */
629   count = MIN (count, priv->len - priv->pos);
630
631   dest = (guint8 *)priv->data + priv->pos;
632   memcpy (dest, buffer, count);
633   priv->pos += count;
634
635   if (priv->pos > priv->valid_len)
636     priv->valid_len = priv->pos;
637
638   return count;
639
640  overflow:
641   /* Overflow: buffer size would need to be bigger than G_MAXSIZE. */
642   g_set_error_literal (error,
643                        G_IO_ERROR,
644                        G_IO_ERROR_NO_SPACE,
645                        _("Amount of memory required to process the write is "
646                          "larger than available address space"));
647   return -1;
648 }
649
650 static gboolean
651 g_memory_output_stream_close (GOutputStream  *stream,
652                               GCancellable   *cancellable,
653                               GError        **error)
654 {
655   return TRUE;
656 }
657
658 static void
659 g_memory_output_stream_close_async (GOutputStream       *stream,
660                                     int                  io_priority,
661                                     GCancellable        *cancellable,
662                                     GAsyncReadyCallback  callback,
663                                     gpointer             data)
664 {
665   GTask *task;
666
667   task = g_task_new (stream, cancellable, callback, data);
668
669   /* will always return TRUE */
670   g_memory_output_stream_close (stream, cancellable, NULL);
671
672   g_task_return_boolean (task, TRUE);
673   g_object_unref (task);
674 }
675
676 static gboolean
677 g_memory_output_stream_close_finish (GOutputStream  *stream,
678                                      GAsyncResult   *result,
679                                      GError        **error)
680 {
681   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
682
683   return g_task_propagate_boolean (G_TASK (result), error);
684 }
685
686 static goffset
687 g_memory_output_stream_tell (GSeekable *seekable)
688 {
689   GMemoryOutputStream *stream;
690   GMemoryOutputStreamPrivate *priv;
691
692   stream = G_MEMORY_OUTPUT_STREAM (seekable);
693   priv = stream->priv;
694
695   return priv->pos;
696 }
697
698 static gboolean
699 g_memory_output_stream_can_seek (GSeekable *seekable)
700 {
701   return TRUE;
702 }
703
704 static gboolean
705 g_memory_output_stream_seek (GSeekable    *seekable,
706                             goffset        offset,
707                             GSeekType      type,
708                             GCancellable  *cancellable,
709                             GError       **error)
710 {
711   GMemoryOutputStream        *stream;
712   GMemoryOutputStreamPrivate *priv;
713   goffset absolute;
714
715   stream = G_MEMORY_OUTPUT_STREAM (seekable);
716   priv = stream->priv;
717
718   switch (type)
719     {
720     case G_SEEK_CUR:
721       absolute = priv->pos + offset;
722       break;
723
724     case G_SEEK_SET:
725       absolute = offset;
726       break;
727
728     case G_SEEK_END:
729       /* For resizable streams, we consider the end to be the data
730        * length.  For fixed-sized streams, we consider the end to be the
731        * size of the buffer.
732        */
733       if (priv->realloc_fn)
734         absolute = priv->valid_len + offset;
735       else
736         absolute = priv->len + offset;
737       break;
738
739     default:
740       g_set_error_literal (error,
741                            G_IO_ERROR,
742                            G_IO_ERROR_INVALID_ARGUMENT,
743                            _("Invalid GSeekType supplied"));
744
745       return FALSE;
746     }
747
748   if (absolute < 0)
749     {
750       g_set_error_literal (error,
751                            G_IO_ERROR,
752                            G_IO_ERROR_INVALID_ARGUMENT,
753                            _("Requested seek before the beginning of the stream"));
754       return FALSE;
755     }
756
757   /* Can't seek past the end of a fixed-size stream.
758    *
759    * Note: seeking to the non-existent byte at the end of a fixed-sized
760    * stream is valid (eg: a 1-byte fixed sized stream can have position
761    * 0 or 1).  Therefore '>' is what we want.
762    * */
763   if (priv->realloc_fn == NULL && absolute > priv->len)
764     {
765       g_set_error_literal (error,
766                            G_IO_ERROR,
767                            G_IO_ERROR_INVALID_ARGUMENT,
768                            _("Requested seek beyond the end of the stream"));
769       return FALSE;
770     }
771
772   priv->pos = absolute;
773
774   return TRUE;
775 }
776
777 static gboolean
778 g_memory_output_stream_can_truncate (GSeekable *seekable)
779 {
780   GMemoryOutputStream *ostream;
781   GMemoryOutputStreamPrivate *priv;
782
783   ostream = G_MEMORY_OUTPUT_STREAM (seekable);
784   priv = ostream->priv;
785
786   return priv->realloc_fn != NULL;
787 }
788
789 static gboolean
790 g_memory_output_stream_truncate (GSeekable     *seekable,
791                                  goffset        offset,
792                                  GCancellable  *cancellable,
793                                  GError       **error)
794 {
795   GMemoryOutputStream *ostream = G_MEMORY_OUTPUT_STREAM (seekable);
796
797   if (!array_resize (ostream, offset, FALSE, error))
798     return FALSE;
799
800   return TRUE;
801 }
802
803 static gboolean
804 g_memory_output_stream_is_writable (GPollableOutputStream *stream)
805 {
806   return TRUE;
807 }
808
809 static GSource *
810 g_memory_output_stream_create_source (GPollableOutputStream *stream,
811                                       GCancellable          *cancellable)
812 {
813   GSource *base_source, *pollable_source;
814
815   base_source = g_timeout_source_new (0);
816   pollable_source = g_pollable_source_new_full (stream, base_source,
817                                                 cancellable);
818   g_source_unref (base_source);
819
820   return pollable_source;
821 }