Change LGPL-2.1+ to LGPL-2.1-or-later
[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  * SPDX-License-Identifier: LGPL-2.1-or-later
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
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 #include "gutilsprivate.h"
35
36
37 /**
38  * SECTION:gmemoryoutputstream
39  * @short_description: Streaming output operations on memory chunks
40  * @include: gio/gio.h
41  * @see_also: #GMemoryInputStream
42  *
43  * #GMemoryOutputStream is a class for using arbitrary
44  * memory chunks as output for GIO streaming output operations.
45  *
46  * As of GLib 2.34, #GMemoryOutputStream trivially implements
47  * #GPollableOutputStream: it always polls as ready.
48  */
49
50 #define MIN_ARRAY_SIZE  16
51
52 enum {
53   PROP_0,
54   PROP_DATA,
55   PROP_SIZE,
56   PROP_DATA_SIZE,
57   PROP_REALLOC_FUNCTION,
58   PROP_DESTROY_FUNCTION
59 };
60
61 struct _GMemoryOutputStreamPrivate
62 {
63   gpointer       data; /* Write buffer */
64   gsize          len; /* Current length of the data buffer. Can change with resizing. */
65   gsize          valid_len; /* The part of data that has been written to */
66   gsize          pos; /* Current position in the stream. Distinct from valid_len,
67                          because the stream is seekable. */
68
69   GReallocFunc   realloc_fn;
70   GDestroyNotify destroy;
71 };
72
73 static void     g_memory_output_stream_set_property (GObject      *object,
74                                                      guint         prop_id,
75                                                      const GValue *value,
76                                                      GParamSpec   *pspec);
77 static void     g_memory_output_stream_get_property (GObject      *object,
78                                                      guint         prop_id,
79                                                      GValue       *value,
80                                                      GParamSpec   *pspec);
81 static void     g_memory_output_stream_finalize     (GObject      *object);
82
83 static gssize   g_memory_output_stream_write       (GOutputStream *stream,
84                                                     const void    *buffer,
85                                                     gsize          count,
86                                                     GCancellable  *cancellable,
87                                                     GError       **error);
88
89 static gboolean g_memory_output_stream_close       (GOutputStream  *stream,
90                                                     GCancellable   *cancellable,
91                                                     GError        **error);
92
93 static void     g_memory_output_stream_close_async  (GOutputStream        *stream,
94                                                      int                   io_priority,
95                                                      GCancellable         *cancellable,
96                                                      GAsyncReadyCallback   callback,
97                                                      gpointer              data);
98 static gboolean g_memory_output_stream_close_finish (GOutputStream        *stream,
99                                                      GAsyncResult         *result,
100                                                      GError              **error);
101
102 static void     g_memory_output_stream_seekable_iface_init (GSeekableIface  *iface);
103 static goffset  g_memory_output_stream_tell                (GSeekable       *seekable);
104 static gboolean g_memory_output_stream_can_seek            (GSeekable       *seekable);
105 static gboolean g_memory_output_stream_seek                (GSeekable       *seekable,
106                                                            goffset          offset,
107                                                            GSeekType        type,
108                                                            GCancellable    *cancellable,
109                                                            GError         **error);
110 static gboolean g_memory_output_stream_can_truncate        (GSeekable       *seekable);
111 static gboolean g_memory_output_stream_truncate            (GSeekable       *seekable,
112                                                            goffset          offset,
113                                                            GCancellable    *cancellable,
114                                                            GError         **error);
115
116 static gboolean g_memory_output_stream_is_writable       (GPollableOutputStream *stream);
117 static GSource *g_memory_output_stream_create_source     (GPollableOutputStream *stream,
118                                                           GCancellable          *cancellable);
119
120 static void g_memory_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface);
121
122 G_DEFINE_TYPE_WITH_CODE (GMemoryOutputStream, g_memory_output_stream, G_TYPE_OUTPUT_STREAM,
123                          G_ADD_PRIVATE (GMemoryOutputStream)
124                          G_IMPLEMENT_INTERFACE (G_TYPE_SEEKABLE,
125                                                 g_memory_output_stream_seekable_iface_init);
126                          G_IMPLEMENT_INTERFACE (G_TYPE_POLLABLE_OUTPUT_STREAM,
127                                                 g_memory_output_stream_pollable_iface_init))
128
129
130 static void
131 g_memory_output_stream_class_init (GMemoryOutputStreamClass *klass)
132 {
133   GOutputStreamClass *ostream_class;
134   GObjectClass *gobject_class;
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_memory_output_stream_get_instance_private (stream);
330   stream->priv->pos = 0;
331   stream->priv->valid_len = 0;
332 }
333
334 /**
335  * g_memory_output_stream_new: (skip)
336  * @data: (nullable): pointer to a chunk of memory to use, or %NULL
337  * @size: the size of @data
338  * @realloc_function: (nullable): a function with realloc() semantics (like g_realloc())
339  *     to be called when @data needs to be grown, or %NULL
340  * @destroy_function: (nullable): a function to be called on @data when the stream is
341  *     finalized, or %NULL
342  *
343  * Creates a new #GMemoryOutputStream.
344  *
345  * In most cases this is not the function you want.  See
346  * g_memory_output_stream_new_resizable() instead.
347  *
348  * If @data is non-%NULL, the stream will use that for its internal storage.
349  *
350  * If @realloc_fn is non-%NULL, it will be used for resizing the internal
351  * storage when necessary and the stream will be considered resizable.
352  * In that case, the stream will start out being (conceptually) empty.
353  * @size is used only as a hint for how big @data is.  Specifically,
354  * seeking to the end of a newly-created stream will seek to zero, not
355  * @size.  Seeking past the end of the stream and then writing will
356  * introduce a zero-filled gap.
357  *
358  * If @realloc_fn is %NULL then the stream is fixed-sized.  Seeking to
359  * the end will seek to @size exactly.  Writing past the end will give
360  * an 'out of space' error.  Attempting to seek past the end will fail.
361  * Unlike the resizable case, seeking to an offset within the stream and
362  * writing will preserve the bytes passed in as @data before that point
363  * and will return them as part of g_memory_output_stream_steal_data().
364  * If you intend to seek you should probably therefore ensure that @data
365  * is properly initialised.
366  *
367  * It is probably only meaningful to provide @data and @size in the case
368  * that you want a fixed-sized stream.  Put another way: if @realloc_fn
369  * is non-%NULL then it makes most sense to give @data as %NULL and
370  * @size as 0 (allowing #GMemoryOutputStream to do the initial
371  * allocation for itself).
372  *
373  * |[<!-- language="C" -->
374  * // a stream that can grow
375  * stream = g_memory_output_stream_new (NULL, 0, realloc, free);
376  *
377  * // another stream that can grow
378  * stream2 = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
379  *
380  * // a fixed-size stream
381  * data = malloc (200);
382  * stream3 = g_memory_output_stream_new (data, 200, NULL, free);
383  * ]|
384  *
385  * Returns: A newly created #GMemoryOutputStream object.
386  **/
387 GOutputStream *
388 g_memory_output_stream_new (gpointer       data,
389                             gsize          size,
390                             GReallocFunc   realloc_function,
391                             GDestroyNotify destroy_function)
392 {
393   GOutputStream *stream;
394
395   stream = g_object_new (G_TYPE_MEMORY_OUTPUT_STREAM,
396                          "data", data,
397                          "size", size,
398                          "realloc-function", realloc_function,
399                          "destroy-function", destroy_function,
400                          NULL);
401
402   return stream;
403 }
404
405 /**
406  * g_memory_output_stream_new_resizable:
407  *
408  * Creates a new #GMemoryOutputStream, using g_realloc() and g_free()
409  * for memory allocation.
410  *
411  * Since: 2.36
412  */
413 GOutputStream *
414 g_memory_output_stream_new_resizable (void)
415 {
416   return g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
417 }
418
419 /**
420  * g_memory_output_stream_get_data:
421  * @ostream: a #GMemoryOutputStream
422  *
423  * Gets any loaded data from the @ostream.
424  *
425  * Note that the returned pointer may become invalid on the next
426  * write or truncate operation on the stream.
427  *
428  * Returns: (transfer none): pointer to the stream's data, or %NULL if the data
429  *    has been stolen
430  **/
431 gpointer
432 g_memory_output_stream_get_data (GMemoryOutputStream *ostream)
433 {
434   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
435
436   return ostream->priv->data;
437 }
438
439 /**
440  * g_memory_output_stream_get_size:
441  * @ostream: a #GMemoryOutputStream
442  *
443  * Gets the size of the currently allocated data area (available from
444  * g_memory_output_stream_get_data()).
445  *
446  * You probably don't want to use this function on resizable streams.
447  * See g_memory_output_stream_get_data_size() instead.  For resizable
448  * streams the size returned by this function is an implementation
449  * detail and may be change at any time in response to operations on the
450  * stream.
451  *
452  * If the stream is fixed-sized (ie: no realloc was passed to
453  * g_memory_output_stream_new()) then this is the maximum size of the
454  * stream and further writes will return %G_IO_ERROR_NO_SPACE.
455  *
456  * In any case, if you want the number of bytes currently written to the
457  * stream, use g_memory_output_stream_get_data_size().
458  *
459  * Returns: the number of bytes allocated for the data buffer
460  */
461 gsize
462 g_memory_output_stream_get_size (GMemoryOutputStream *ostream)
463 {
464   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
465
466   return ostream->priv->len;
467 }
468
469 /**
470  * g_memory_output_stream_get_data_size:
471  * @ostream: a #GMemoryOutputStream
472  *
473  * Returns the number of bytes from the start up to including the last
474  * byte written in the stream that has not been truncated away.
475  *
476  * Returns: the number of bytes written to the stream
477  *
478  * Since: 2.18
479  */
480 gsize
481 g_memory_output_stream_get_data_size (GMemoryOutputStream *ostream)
482 {
483   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
484
485   return ostream->priv->valid_len;
486 }
487
488 /**
489  * g_memory_output_stream_steal_data:
490  * @ostream: a #GMemoryOutputStream
491  *
492  * Gets any loaded data from the @ostream. Ownership of the data
493  * is transferred to the caller; when no longer needed it must be
494  * freed using the free function set in @ostream's
495  * #GMemoryOutputStream:destroy-function property.
496  *
497  * @ostream must be closed before calling this function.
498  *
499  * Returns: (transfer full): the stream's data, or %NULL if it has previously
500  *    been stolen
501  *
502  * Since: 2.26
503  **/
504 gpointer
505 g_memory_output_stream_steal_data (GMemoryOutputStream *ostream)
506 {
507   gpointer data;
508
509   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
510   g_return_val_if_fail (g_output_stream_is_closed (G_OUTPUT_STREAM (ostream)), NULL);
511
512   data = ostream->priv->data;
513   ostream->priv->data = NULL;
514
515   return data;
516 }
517
518 /**
519  * g_memory_output_stream_steal_as_bytes:
520  * @ostream: a #GMemoryOutputStream
521  *
522  * Returns data from the @ostream as a #GBytes. @ostream must be
523  * closed before calling this function.
524  *
525  * Returns: (transfer full): the stream's data
526  *
527  * Since: 2.34
528  **/
529 GBytes *
530 g_memory_output_stream_steal_as_bytes (GMemoryOutputStream *ostream)
531 {
532   GBytes *result;
533
534   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
535   g_return_val_if_fail (g_output_stream_is_closed (G_OUTPUT_STREAM (ostream)), NULL);
536
537   result = g_bytes_new_with_free_func (ostream->priv->data,
538                                        ostream->priv->valid_len,
539                                        ostream->priv->destroy,
540                                        ostream->priv->data);
541   ostream->priv->data = NULL;
542
543   return result;
544 }
545
546 static gboolean
547 array_resize (GMemoryOutputStream  *ostream,
548               gsize                 size,
549               gboolean              allow_partial,
550               GError              **error)
551 {
552   GMemoryOutputStreamPrivate *priv;
553   gpointer data;
554   gsize len;
555
556   priv = ostream->priv;
557
558   if (priv->len == size)
559     return TRUE;
560
561   if (!priv->realloc_fn)
562     {
563       if (allow_partial &&
564           priv->pos < priv->len)
565         return TRUE; /* Short write */
566
567       g_set_error_literal (error,
568                            G_IO_ERROR,
569                            G_IO_ERROR_NO_SPACE,
570                            _("Memory output stream not resizable"));
571       return FALSE;
572     }
573
574   len = priv->len;
575   data = priv->realloc_fn (priv->data, size);
576
577   if (size > 0 && !data)
578     {
579       if (allow_partial &&
580           priv->pos < priv->len)
581         return TRUE; /* Short write */
582
583       g_set_error_literal (error,
584                            G_IO_ERROR,
585                            G_IO_ERROR_NO_SPACE,
586                            _("Failed to resize memory output stream"));
587       return FALSE;
588     }
589
590   if (size > len)
591     memset ((guint8 *)data + len, 0, size - len);
592
593   priv->data = data;
594   priv->len = size;
595
596   if (priv->len < priv->valid_len)
597     priv->valid_len = priv->len;
598
599   return TRUE;
600 }
601
602 static gssize
603 g_memory_output_stream_write (GOutputStream  *stream,
604                               const void     *buffer,
605                               gsize           count,
606                               GCancellable   *cancellable,
607                               GError        **error)
608 {
609   GMemoryOutputStream        *ostream;
610   GMemoryOutputStreamPrivate *priv;
611   guint8   *dest;
612   gsize new_size;
613
614   ostream = G_MEMORY_OUTPUT_STREAM (stream);
615   priv = ostream->priv;
616
617   if (count == 0)
618     return 0;
619
620   /* Check for address space overflow, but only if the buffer is resizable.
621      Otherwise we just do a short write and don't worry. */
622   if (priv->realloc_fn && priv->pos + count < priv->pos)
623     goto overflow;
624
625   if (priv->pos + count > priv->len)
626     {
627       /* At least enough to fit the write, rounded up for greater than
628        * linear growth.
629        *
630        * Assuming that we're using something like realloc(), the kernel
631        * will overcommit memory to us, so doubling the size each time
632        * will keep the number of realloc calls low without wasting too
633        * much memory.
634        */
635       new_size = g_nearest_pow (priv->pos + count);
636       /* Check for overflow again. We have checked if
637          pos + count > G_MAXSIZE, but now check if g_nearest_pow () has
638          overflowed */
639       if (new_size == 0)
640         goto overflow;
641
642       new_size = MAX (new_size, MIN_ARRAY_SIZE);
643       if (!array_resize (ostream, new_size, TRUE, error))
644         return -1;
645     }
646
647   /* Make sure we handle short writes if the array_resize
648      only added part of the required memory */
649   count = MIN (count, priv->len - priv->pos);
650
651   dest = (guint8 *)priv->data + priv->pos;
652   memcpy (dest, buffer, count);
653   priv->pos += count;
654
655   if (priv->pos > priv->valid_len)
656     priv->valid_len = priv->pos;
657
658   return count;
659
660  overflow:
661   /* Overflow: buffer size would need to be bigger than G_MAXSIZE. */
662   g_set_error_literal (error,
663                        G_IO_ERROR,
664                        G_IO_ERROR_NO_SPACE,
665                        _("Amount of memory required to process the write is "
666                          "larger than available address space"));
667   return -1;
668 }
669
670 static gboolean
671 g_memory_output_stream_close (GOutputStream  *stream,
672                               GCancellable   *cancellable,
673                               GError        **error)
674 {
675   return TRUE;
676 }
677
678 static void
679 g_memory_output_stream_close_async (GOutputStream       *stream,
680                                     int                  io_priority,
681                                     GCancellable        *cancellable,
682                                     GAsyncReadyCallback  callback,
683                                     gpointer             data)
684 {
685   GTask *task;
686
687   task = g_task_new (stream, cancellable, callback, data);
688   g_task_set_source_tag (task, g_memory_output_stream_close_async);
689
690   /* will always return TRUE */
691   g_memory_output_stream_close (stream, cancellable, NULL);
692
693   g_task_return_boolean (task, TRUE);
694   g_object_unref (task);
695 }
696
697 static gboolean
698 g_memory_output_stream_close_finish (GOutputStream  *stream,
699                                      GAsyncResult   *result,
700                                      GError        **error)
701 {
702   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
703
704   return g_task_propagate_boolean (G_TASK (result), error);
705 }
706
707 static goffset
708 g_memory_output_stream_tell (GSeekable *seekable)
709 {
710   GMemoryOutputStream *stream;
711   GMemoryOutputStreamPrivate *priv;
712
713   stream = G_MEMORY_OUTPUT_STREAM (seekable);
714   priv = stream->priv;
715
716   return priv->pos;
717 }
718
719 static gboolean
720 g_memory_output_stream_can_seek (GSeekable *seekable)
721 {
722   return TRUE;
723 }
724
725 static gboolean
726 g_memory_output_stream_seek (GSeekable    *seekable,
727                              goffset        offset,
728                              GSeekType      type,
729                              GCancellable  *cancellable,
730                              GError       **error)
731 {
732   GMemoryOutputStream        *stream;
733   GMemoryOutputStreamPrivate *priv;
734   goffset absolute;
735
736   stream = G_MEMORY_OUTPUT_STREAM (seekable);
737   priv = stream->priv;
738
739   switch (type)
740     {
741     case G_SEEK_CUR:
742       absolute = priv->pos + offset;
743       break;
744
745     case G_SEEK_SET:
746       absolute = offset;
747       break;
748
749     case G_SEEK_END:
750       /* For resizable streams, we consider the end to be the data
751        * length.  For fixed-sized streams, we consider the end to be the
752        * size of the buffer.
753        */
754       if (priv->realloc_fn)
755         absolute = priv->valid_len + offset;
756       else
757         absolute = priv->len + offset;
758       break;
759
760     default:
761       g_set_error_literal (error,
762                            G_IO_ERROR,
763                            G_IO_ERROR_INVALID_ARGUMENT,
764                            _("Invalid GSeekType supplied"));
765
766       return FALSE;
767     }
768
769   if (absolute < 0)
770     {
771       g_set_error_literal (error,
772                            G_IO_ERROR,
773                            G_IO_ERROR_INVALID_ARGUMENT,
774                            _("Requested seek before the beginning of the stream"));
775       return FALSE;
776     }
777
778   /* Can't seek past the end of a fixed-size stream.
779    *
780    * Note: seeking to the non-existent byte at the end of a fixed-sized
781    * stream is valid (eg: a 1-byte fixed sized stream can have position
782    * 0 or 1).  Therefore '>' is what we want.
783    * */
784   if (priv->realloc_fn == NULL && (gsize) absolute > priv->len)
785     {
786       g_set_error_literal (error,
787                            G_IO_ERROR,
788                            G_IO_ERROR_INVALID_ARGUMENT,
789                            _("Requested seek beyond the end of the stream"));
790       return FALSE;
791     }
792
793   priv->pos = absolute;
794
795   return TRUE;
796 }
797
798 static gboolean
799 g_memory_output_stream_can_truncate (GSeekable *seekable)
800 {
801   GMemoryOutputStream *ostream;
802   GMemoryOutputStreamPrivate *priv;
803
804   ostream = G_MEMORY_OUTPUT_STREAM (seekable);
805   priv = ostream->priv;
806
807   /* We do not allow truncation of fixed-sized streams */
808   return priv->realloc_fn != NULL;
809 }
810
811 static gboolean
812 g_memory_output_stream_truncate (GSeekable     *seekable,
813                                  goffset        offset,
814                                  GCancellable  *cancellable,
815                                  GError       **error)
816 {
817   GMemoryOutputStream *ostream = G_MEMORY_OUTPUT_STREAM (seekable);
818
819   if (!array_resize (ostream, offset, FALSE, error))
820     return FALSE;
821
822   ostream->priv->valid_len = offset;
823
824   return TRUE;
825 }
826
827 static gboolean
828 g_memory_output_stream_is_writable (GPollableOutputStream *stream)
829 {
830   return TRUE;
831 }
832
833 static GSource *
834 g_memory_output_stream_create_source (GPollableOutputStream *stream,
835                                       GCancellable          *cancellable)
836 {
837   GSource *base_source, *pollable_source;
838
839   base_source = g_timeout_source_new (0);
840   pollable_source = g_pollable_source_new_full (stream, base_source, cancellable);
841   g_source_unref (base_source);
842
843   return pollable_source;
844 }