[kdbus] KDBUS_ITEM_PAYLOAD_OFF items are (once again) relative to msg header
[platform/upstream/glib.git] / gio / goutputstream.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, see <http://www.gnu.org/licenses/>.
17  *
18  * Author: Alexander Larsson <alexl@redhat.com>
19  */
20
21 #include "config.h"
22 #include <string.h>
23 #include "goutputstream.h"
24 #include "gcancellable.h"
25 #include "gasyncresult.h"
26 #include "gtask.h"
27 #include "ginputstream.h"
28 #include "gioerror.h"
29 #include "gioprivate.h"
30 #include "glibintl.h"
31 #include "gpollableoutputstream.h"
32
33 /**
34  * SECTION:goutputstream
35  * @short_description: Base class for implementing streaming output
36  * @include: gio/gio.h
37  *
38  * #GOutputStream has functions to write to a stream (g_output_stream_write()),
39  * to close a stream (g_output_stream_close()) and to flush pending writes
40  * (g_output_stream_flush()). 
41  *
42  * To copy the content of an input stream to an output stream without 
43  * manually handling the reads and writes, use g_output_stream_splice(). 
44  *
45  * All of these functions have async variants too.
46  **/
47
48 struct _GOutputStreamPrivate {
49   guint closed : 1;
50   guint pending : 1;
51   guint closing : 1;
52   GAsyncReadyCallback outstanding_callback;
53 };
54
55 G_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE (GOutputStream, g_output_stream, G_TYPE_OBJECT)
56
57 static gssize   g_output_stream_real_splice        (GOutputStream             *stream,
58                                                     GInputStream              *source,
59                                                     GOutputStreamSpliceFlags   flags,
60                                                     GCancellable              *cancellable,
61                                                     GError                   **error);
62 static void     g_output_stream_real_write_async   (GOutputStream             *stream,
63                                                     const void                *buffer,
64                                                     gsize                      count,
65                                                     int                        io_priority,
66                                                     GCancellable              *cancellable,
67                                                     GAsyncReadyCallback        callback,
68                                                     gpointer                   data);
69 static gssize   g_output_stream_real_write_finish  (GOutputStream             *stream,
70                                                     GAsyncResult              *result,
71                                                     GError                   **error);
72 static void     g_output_stream_real_splice_async  (GOutputStream             *stream,
73                                                     GInputStream              *source,
74                                                     GOutputStreamSpliceFlags   flags,
75                                                     int                        io_priority,
76                                                     GCancellable              *cancellable,
77                                                     GAsyncReadyCallback        callback,
78                                                     gpointer                   data);
79 static gssize   g_output_stream_real_splice_finish (GOutputStream             *stream,
80                                                     GAsyncResult              *result,
81                                                     GError                   **error);
82 static void     g_output_stream_real_flush_async   (GOutputStream             *stream,
83                                                     int                        io_priority,
84                                                     GCancellable              *cancellable,
85                                                     GAsyncReadyCallback        callback,
86                                                     gpointer                   data);
87 static gboolean g_output_stream_real_flush_finish  (GOutputStream             *stream,
88                                                     GAsyncResult              *result,
89                                                     GError                   **error);
90 static void     g_output_stream_real_close_async   (GOutputStream             *stream,
91                                                     int                        io_priority,
92                                                     GCancellable              *cancellable,
93                                                     GAsyncReadyCallback        callback,
94                                                     gpointer                   data);
95 static gboolean g_output_stream_real_close_finish  (GOutputStream             *stream,
96                                                     GAsyncResult              *result,
97                                                     GError                   **error);
98 static gboolean g_output_stream_internal_close     (GOutputStream             *stream,
99                                                     GCancellable              *cancellable,
100                                                     GError                   **error);
101 static void     g_output_stream_internal_close_async (GOutputStream           *stream,
102                                                       int                      io_priority,
103                                                       GCancellable            *cancellable,
104                                                       GAsyncReadyCallback      callback,
105                                                       gpointer                 data);
106 static gboolean g_output_stream_internal_close_finish (GOutputStream          *stream,
107                                                        GAsyncResult           *result,
108                                                        GError                **error);
109
110 static void
111 g_output_stream_dispose (GObject *object)
112 {
113   GOutputStream *stream;
114
115   stream = G_OUTPUT_STREAM (object);
116   
117   if (!stream->priv->closed)
118     g_output_stream_close (stream, NULL, NULL);
119
120   G_OBJECT_CLASS (g_output_stream_parent_class)->dispose (object);
121 }
122
123 static void
124 g_output_stream_class_init (GOutputStreamClass *klass)
125 {
126   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
127
128   gobject_class->dispose = g_output_stream_dispose;
129
130   klass->splice = g_output_stream_real_splice;
131   
132   klass->write_async = g_output_stream_real_write_async;
133   klass->write_finish = g_output_stream_real_write_finish;
134   klass->splice_async = g_output_stream_real_splice_async;
135   klass->splice_finish = g_output_stream_real_splice_finish;
136   klass->flush_async = g_output_stream_real_flush_async;
137   klass->flush_finish = g_output_stream_real_flush_finish;
138   klass->close_async = g_output_stream_real_close_async;
139   klass->close_finish = g_output_stream_real_close_finish;
140 }
141
142 static void
143 g_output_stream_init (GOutputStream *stream)
144 {
145   stream->priv = g_output_stream_get_instance_private (stream);
146 }
147
148 /**
149  * g_output_stream_write:
150  * @stream: a #GOutputStream.
151  * @buffer: (array length=count) (element-type guint8): the buffer containing the data to write. 
152  * @count: the number of bytes to write
153  * @cancellable: (allow-none): optional cancellable object
154  * @error: location to store the error occurring, or %NULL to ignore
155  *
156  * Tries to write @count bytes from @buffer into the stream. Will block
157  * during the operation.
158  * 
159  * If count is 0, returns 0 and does nothing. A value of @count
160  * larger than %G_MAXSSIZE will cause a %G_IO_ERROR_INVALID_ARGUMENT error.
161  *
162  * On success, the number of bytes written to the stream is returned.
163  * It is not an error if this is not the same as the requested size, as it
164  * can happen e.g. on a partial I/O error, or if there is not enough
165  * storage in the stream. All writes block until at least one byte
166  * is written or an error occurs; 0 is never returned (unless
167  * @count is 0).
168  * 
169  * If @cancellable is not %NULL, then the operation can be cancelled by
170  * triggering the cancellable object from another thread. If the operation
171  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. If an
172  * operation was partially finished when the operation was cancelled the
173  * partial result will be returned, without an error.
174  *
175  * On error -1 is returned and @error is set accordingly.
176  * 
177  * Virtual: write_fn
178  *
179  * Returns: Number of bytes written, or -1 on error
180  **/
181 gssize
182 g_output_stream_write (GOutputStream  *stream,
183                        const void     *buffer,
184                        gsize           count,
185                        GCancellable   *cancellable,
186                        GError        **error)
187 {
188   GOutputStreamClass *class;
189   gssize res;
190
191   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), -1);
192   g_return_val_if_fail (buffer != NULL, 0);
193
194   if (count == 0)
195     return 0;
196   
197   if (((gssize) count) < 0)
198     {
199       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
200                    _("Too large count value passed to %s"), G_STRFUNC);
201       return -1;
202     }
203
204   class = G_OUTPUT_STREAM_GET_CLASS (stream);
205
206   if (class->write_fn == NULL) 
207     {
208       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
209                            _("Output stream doesn't implement write"));
210       return -1;
211     }
212   
213   if (!g_output_stream_set_pending (stream, error))
214     return -1;
215   
216   if (cancellable)
217     g_cancellable_push_current (cancellable);
218   
219   res = class->write_fn (stream, buffer, count, cancellable, error);
220   
221   if (cancellable)
222     g_cancellable_pop_current (cancellable);
223   
224   g_output_stream_clear_pending (stream);
225
226   return res; 
227 }
228
229 /**
230  * g_output_stream_write_all:
231  * @stream: a #GOutputStream.
232  * @buffer: (array length=count) (element-type guint8): the buffer containing the data to write. 
233  * @count: the number of bytes to write
234  * @bytes_written: (out): location to store the number of bytes that was 
235  *     written to the stream
236  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
237  * @error: location to store the error occurring, or %NULL to ignore
238  *
239  * Tries to write @count bytes from @buffer into the stream. Will block
240  * during the operation.
241  * 
242  * This function is similar to g_output_stream_write(), except it tries to
243  * write as many bytes as requested, only stopping on an error.
244  *
245  * On a successful write of @count bytes, %TRUE is returned, and @bytes_written
246  * is set to @count.
247  * 
248  * If there is an error during the operation %FALSE is returned and @error
249  * is set to indicate the error status.
250  *
251  * As a special exception to the normal conventions for functions that
252  * use #GError, if this function returns %FALSE (and sets @error) then
253  * @bytes_written will be set to the number of bytes that were
254  * successfully written before the error was encountered.  This
255  * functionality is only available from C.  If you need it from another
256  * language then you must write your own loop around
257  * g_output_stream_write().
258  *
259  * Returns: %TRUE on success, %FALSE if there was an error
260  **/
261 gboolean
262 g_output_stream_write_all (GOutputStream  *stream,
263                            const void     *buffer,
264                            gsize           count,
265                            gsize          *bytes_written,
266                            GCancellable   *cancellable,
267                            GError        **error)
268 {
269   gsize _bytes_written;
270   gssize res;
271
272   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
273   g_return_val_if_fail (buffer != NULL, FALSE);
274
275   _bytes_written = 0;
276   while (_bytes_written < count)
277     {
278       res = g_output_stream_write (stream, (char *)buffer + _bytes_written, count - _bytes_written,
279                                    cancellable, error);
280       if (res == -1)
281         {
282           if (bytes_written)
283             *bytes_written = _bytes_written;
284           return FALSE;
285         }
286       
287       if (res == 0)
288         g_warning ("Write returned zero without error");
289
290       _bytes_written += res;
291     }
292   
293   if (bytes_written)
294     *bytes_written = _bytes_written;
295
296   return TRUE;
297 }
298
299 /**
300  * g_output_stream_printf:
301  * @stream: a #GOutputStream.
302  * @bytes_written: (out): location to store the number of bytes that was
303  *     written to the stream
304  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
305  * @error: location to store the error occurring, or %NULL to ignore
306  * @format: the format string. See the printf() documentation
307  * @...: the parameters to insert into the format string
308  *
309  * This is a utility function around g_output_stream_write_all(). It
310  * uses g_strdup_vprintf() to turn @format and @... into a string that
311  * is then written to @stream.
312  *
313  * See the documentation of g_output_stream_write_all() about the
314  * behavior of the actual write operation.
315  *
316  * Note that partial writes cannot be properly checked with this
317  * function due to the variable length of the written string, if you
318  * need precise control over partial write failures, you need to
319  * create you own printf()-like wrapper around g_output_stream_write()
320  * or g_output_stream_write_all().
321  *
322  * Since: 2.40
323  *
324  * Returns: %TRUE on success, %FALSE if there was an error
325  **/
326 gboolean
327 g_output_stream_printf (GOutputStream  *stream,
328                         gsize          *bytes_written,
329                         GCancellable   *cancellable,
330                         GError        **error,
331                         const gchar    *format,
332                         ...)
333 {
334   va_list  args;
335   gboolean success;
336
337   va_start (args, format);
338   success = g_output_stream_vprintf (stream, bytes_written, cancellable,
339                                      error, format, args);
340   va_end (args);
341
342   return success;
343 }
344
345 /**
346  * g_output_stream_vprintf:
347  * @stream: a #GOutputStream.
348  * @bytes_written: (out): location to store the number of bytes that was
349  *     written to the stream
350  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
351  * @error: location to store the error occurring, or %NULL to ignore
352  * @format: the format string. See the printf() documentation
353  * @args: the parameters to insert into the format string
354  *
355  * This is a utility function around g_output_stream_write_all(). It
356  * uses g_strdup_vprintf() to turn @format and @args into a string that
357  * is then written to @stream.
358  *
359  * See the documentation of g_output_stream_write_all() about the
360  * behavior of the actual write operation.
361  *
362  * Note that partial writes cannot be properly checked with this
363  * function due to the variable length of the written string, if you
364  * need precise control over partial write failures, you need to
365  * create you own printf()-like wrapper around g_output_stream_write()
366  * or g_output_stream_write_all().
367  *
368  * Since: 2.40
369  *
370  * Returns: %TRUE on success, %FALSE if there was an error
371  **/
372 gboolean
373 g_output_stream_vprintf (GOutputStream  *stream,
374                          gsize          *bytes_written,
375                          GCancellable   *cancellable,
376                          GError        **error,
377                          const gchar    *format,
378                          va_list         args)
379 {
380   gchar    *text;
381   gboolean  success;
382
383   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
384   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (stream), FALSE);
385   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
386   g_return_val_if_fail (format != NULL, FALSE);
387
388   text = g_strdup_vprintf (format, args);
389   success = g_output_stream_write_all (stream,
390                                        text, strlen (text),
391                                        bytes_written, cancellable, error);
392   g_free (text);
393
394   return success;
395 }
396
397 /**
398  * g_output_stream_write_bytes:
399  * @stream: a #GOutputStream.
400  * @bytes: the #GBytes to write
401  * @cancellable: (allow-none): optional cancellable object
402  * @error: location to store the error occurring, or %NULL to ignore
403  *
404  * A wrapper function for g_output_stream_write() which takes a
405  * #GBytes as input.  This can be more convenient for use by language
406  * bindings or in other cases where the refcounted nature of #GBytes
407  * is helpful over a bare pointer interface.
408  *
409  * However, note that this function may still perform partial writes,
410  * just like g_output_stream_write().  If that occurs, to continue
411  * writing, you will need to create a new #GBytes containing just the
412  * remaining bytes, using g_bytes_new_from_bytes(). Passing the same
413  * #GBytes instance multiple times potentially can result in duplicated
414  * data in the output stream.
415  *
416  * Returns: Number of bytes written, or -1 on error
417  **/
418 gssize
419 g_output_stream_write_bytes (GOutputStream  *stream,
420                              GBytes         *bytes,
421                              GCancellable   *cancellable,
422                              GError        **error)
423 {
424   gsize size;
425   gconstpointer data;
426
427   data = g_bytes_get_data (bytes, &size);
428
429   return g_output_stream_write (stream,
430                                 data, size,
431                                 cancellable,
432                                 error);
433 }
434
435 /**
436  * g_output_stream_flush:
437  * @stream: a #GOutputStream.
438  * @cancellable: (allow-none): optional cancellable object
439  * @error: location to store the error occurring, or %NULL to ignore
440  *
441  * Forces a write of all user-space buffered data for the given
442  * @stream. Will block during the operation. Closing the stream will
443  * implicitly cause a flush.
444  *
445  * This function is optional for inherited classes.
446  * 
447  * If @cancellable is not %NULL, then the operation can be cancelled by
448  * triggering the cancellable object from another thread. If the operation
449  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
450  *
451  * Returns: %TRUE on success, %FALSE on error
452  **/
453 gboolean
454 g_output_stream_flush (GOutputStream  *stream,
455                        GCancellable   *cancellable,
456                        GError        **error)
457 {
458   GOutputStreamClass *class;
459   gboolean res;
460
461   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
462
463   if (!g_output_stream_set_pending (stream, error))
464     return FALSE;
465   
466   class = G_OUTPUT_STREAM_GET_CLASS (stream);
467
468   res = TRUE;
469   if (class->flush)
470     {
471       if (cancellable)
472         g_cancellable_push_current (cancellable);
473       
474       res = class->flush (stream, cancellable, error);
475       
476       if (cancellable)
477         g_cancellable_pop_current (cancellable);
478     }
479   
480   g_output_stream_clear_pending (stream);
481
482   return res;
483 }
484
485 /**
486  * g_output_stream_splice:
487  * @stream: a #GOutputStream.
488  * @source: a #GInputStream.
489  * @flags: a set of #GOutputStreamSpliceFlags.
490  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
491  * @error: a #GError location to store the error occurring, or %NULL to
492  * ignore.
493  *
494  * Splices an input stream into an output stream.
495  *
496  * Returns: a #gssize containing the size of the data spliced, or
497  *     -1 if an error occurred. Note that if the number of bytes
498  *     spliced is greater than %G_MAXSSIZE, then that will be
499  *     returned, and there is no way to determine the actual number
500  *     of bytes spliced.
501  **/
502 gssize
503 g_output_stream_splice (GOutputStream             *stream,
504                         GInputStream              *source,
505                         GOutputStreamSpliceFlags   flags,
506                         GCancellable              *cancellable,
507                         GError                   **error)
508 {
509   GOutputStreamClass *class;
510   gssize bytes_copied;
511
512   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), -1);
513   g_return_val_if_fail (G_IS_INPUT_STREAM (source), -1);
514
515   if (g_input_stream_is_closed (source))
516     {
517       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
518                            _("Source stream is already closed"));
519       return -1;
520     }
521
522   if (!g_output_stream_set_pending (stream, error))
523     return -1;
524
525   class = G_OUTPUT_STREAM_GET_CLASS (stream);
526
527   if (cancellable)
528     g_cancellable_push_current (cancellable);
529
530   bytes_copied = class->splice (stream, source, flags, cancellable, error);
531
532   if (cancellable)
533     g_cancellable_pop_current (cancellable);
534
535   g_output_stream_clear_pending (stream);
536
537   return bytes_copied;
538 }
539
540 static gssize
541 g_output_stream_real_splice (GOutputStream             *stream,
542                              GInputStream              *source,
543                              GOutputStreamSpliceFlags   flags,
544                              GCancellable              *cancellable,
545                              GError                   **error)
546 {
547   GOutputStreamClass *class = G_OUTPUT_STREAM_GET_CLASS (stream);
548   gssize n_read, n_written;
549   gsize bytes_copied;
550   char buffer[8192], *p;
551   gboolean res;
552
553   bytes_copied = 0;
554   if (class->write_fn == NULL)
555     {
556       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
557                            _("Output stream doesn't implement write"));
558       res = FALSE;
559       goto notsupported;
560     }
561
562   res = TRUE;
563   do
564     {
565       n_read = g_input_stream_read (source, buffer, sizeof (buffer), cancellable, error);
566       if (n_read == -1)
567         {
568           res = FALSE;
569           break;
570         }
571
572       if (n_read == 0)
573         break;
574
575       p = buffer;
576       while (n_read > 0)
577         {
578           n_written = class->write_fn (stream, p, n_read, cancellable, error);
579           if (n_written == -1)
580             {
581               res = FALSE;
582               break;
583             }
584
585           p += n_written;
586           n_read -= n_written;
587           bytes_copied += n_written;
588         }
589
590       if (bytes_copied > G_MAXSSIZE)
591         bytes_copied = G_MAXSSIZE;
592     }
593   while (res);
594
595  notsupported:
596   if (!res)
597     error = NULL; /* Ignore further errors */
598
599   if (flags & G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE)
600     {
601       /* Don't care about errors in source here */
602       g_input_stream_close (source, cancellable, NULL);
603     }
604
605   if (flags & G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET)
606     {
607       /* But write errors on close are bad! */
608       res = g_output_stream_internal_close (stream, cancellable, error);
609     }
610
611   if (res)
612     return bytes_copied;
613
614   return -1;
615 }
616
617 /* Must always be called inside
618  * g_output_stream_set_pending()/g_output_stream_clear_pending(). */
619 static gboolean
620 g_output_stream_internal_close (GOutputStream  *stream,
621                                 GCancellable   *cancellable,
622                                 GError        **error)
623 {
624   GOutputStreamClass *class;
625   gboolean res;
626
627   if (stream->priv->closed)
628     return TRUE;
629
630   class = G_OUTPUT_STREAM_GET_CLASS (stream);
631
632   stream->priv->closing = TRUE;
633
634   if (cancellable)
635     g_cancellable_push_current (cancellable);
636
637   if (class->flush)
638     res = class->flush (stream, cancellable, error);
639   else
640     res = TRUE;
641
642   if (!res)
643     {
644       /* flushing caused the error that we want to return,
645        * but we still want to close the underlying stream if possible
646        */
647       if (class->close_fn)
648         class->close_fn (stream, cancellable, NULL);
649     }
650   else
651     {
652       res = TRUE;
653       if (class->close_fn)
654         res = class->close_fn (stream, cancellable, error);
655     }
656
657   if (cancellable)
658     g_cancellable_pop_current (cancellable);
659
660   stream->priv->closing = FALSE;
661   stream->priv->closed = TRUE;
662
663   return res;
664 }
665
666 /**
667  * g_output_stream_close:
668  * @stream: A #GOutputStream.
669  * @cancellable: (allow-none): optional cancellable object
670  * @error: location to store the error occurring, or %NULL to ignore
671  *
672  * Closes the stream, releasing resources related to it.
673  *
674  * Once the stream is closed, all other operations will return %G_IO_ERROR_CLOSED.
675  * Closing a stream multiple times will not return an error.
676  *
677  * Closing a stream will automatically flush any outstanding buffers in the
678  * stream.
679  *
680  * Streams will be automatically closed when the last reference
681  * is dropped, but you might want to call this function to make sure 
682  * resources are released as early as possible.
683  *
684  * Some streams might keep the backing store of the stream (e.g. a file descriptor)
685  * open after the stream is closed. See the documentation for the individual
686  * stream for details.
687  *
688  * On failure the first error that happened will be reported, but the close
689  * operation will finish as much as possible. A stream that failed to
690  * close will still return %G_IO_ERROR_CLOSED for all operations. Still, it
691  * is important to check and report the error to the user, otherwise
692  * there might be a loss of data as all data might not be written.
693  * 
694  * If @cancellable is not %NULL, then the operation can be cancelled by
695  * triggering the cancellable object from another thread. If the operation
696  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
697  * Cancelling a close will still leave the stream closed, but there some streams
698  * can use a faster close that doesn't block to e.g. check errors. On
699  * cancellation (as with any error) there is no guarantee that all written
700  * data will reach the target. 
701  *
702  * Returns: %TRUE on success, %FALSE on failure
703  **/
704 gboolean
705 g_output_stream_close (GOutputStream  *stream,
706                        GCancellable   *cancellable,
707                        GError        **error)
708 {
709   gboolean res;
710
711   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
712
713   if (stream->priv->closed)
714     return TRUE;
715
716   if (!g_output_stream_set_pending (stream, error))
717     return FALSE;
718
719   res = g_output_stream_internal_close (stream, cancellable, error);
720
721   g_output_stream_clear_pending (stream);
722   
723   return res;
724 }
725
726 static void
727 async_ready_write_callback_wrapper (GObject      *source_object,
728                                     GAsyncResult *res,
729                                     gpointer      user_data)
730 {
731   GOutputStream *stream = G_OUTPUT_STREAM (source_object);
732   GOutputStreamClass *class;
733   GTask *task = user_data;
734   gssize nwrote;
735   GError *error = NULL;
736
737   g_output_stream_clear_pending (stream);
738   
739   if (g_async_result_legacy_propagate_error (res, &error))
740     nwrote = -1;
741   else
742     {
743       class = G_OUTPUT_STREAM_GET_CLASS (stream);
744       nwrote = class->write_finish (stream, res, &error);
745     }
746
747   if (nwrote >= 0)
748     g_task_return_int (task, nwrote);
749   else
750     g_task_return_error (task, error);
751   g_object_unref (task);
752 }
753
754 /**
755  * g_output_stream_write_async:
756  * @stream: A #GOutputStream.
757  * @buffer: (array length=count) (element-type guint8): the buffer containing the data to write. 
758  * @count: the number of bytes to write
759  * @io_priority: the io priority of the request.
760  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
761  * @callback: (scope async): callback to call when the request is satisfied
762  * @user_data: (closure): the data to pass to callback function
763  *
764  * Request an asynchronous write of @count bytes from @buffer into 
765  * the stream. When the operation is finished @callback will be called.
766  * You can then call g_output_stream_write_finish() to get the result of the 
767  * operation.
768  *
769  * During an async request no other sync and async calls are allowed, 
770  * and will result in %G_IO_ERROR_PENDING errors. 
771  *
772  * A value of @count larger than %G_MAXSSIZE will cause a 
773  * %G_IO_ERROR_INVALID_ARGUMENT error.
774  *
775  * On success, the number of bytes written will be passed to the
776  * @callback. It is not an error if this is not the same as the 
777  * requested size, as it can happen e.g. on a partial I/O error, 
778  * but generally we try to write as many bytes as requested. 
779  *
780  * You are guaranteed that this method will never fail with
781  * %G_IO_ERROR_WOULD_BLOCK - if @stream can't accept more data, the
782  * method will just wait until this changes.
783  *
784  * Any outstanding I/O request with higher priority (lower numerical 
785  * value) will be executed before an outstanding request with lower 
786  * priority. Default priority is %G_PRIORITY_DEFAULT.
787  *
788  * The asyncronous methods have a default fallback that uses threads 
789  * to implement asynchronicity, so they are optional for inheriting 
790  * classes. However, if you override one you must override all.
791  *
792  * For the synchronous, blocking version of this function, see 
793  * g_output_stream_write().
794  *
795  * Note that no copy of @buffer will be made, so it must stay valid
796  * until @callback is called. See g_output_stream_write_bytes_async()
797  * for a #GBytes version that will automatically hold a reference to
798  * the contents (without copying) for the duration of the call.
799  */
800 void
801 g_output_stream_write_async (GOutputStream       *stream,
802                              const void          *buffer,
803                              gsize                count,
804                              int                  io_priority,
805                              GCancellable        *cancellable,
806                              GAsyncReadyCallback  callback,
807                              gpointer             user_data)
808 {
809   GOutputStreamClass *class;
810   GError *error = NULL;
811   GTask *task;
812
813   g_return_if_fail (G_IS_OUTPUT_STREAM (stream));
814   g_return_if_fail (buffer != NULL);
815
816   task = g_task_new (stream, cancellable, callback, user_data);
817   g_task_set_source_tag (task, g_output_stream_write_async);
818   g_task_set_priority (task, io_priority);
819
820   if (count == 0)
821     {
822       g_task_return_int (task, 0);
823       g_object_unref (task);
824       return;
825     }
826
827   if (((gssize) count) < 0)
828     {
829       g_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
830                                _("Too large count value passed to %s"),
831                                G_STRFUNC);
832       g_object_unref (task);
833       return;
834     }
835
836   if (!g_output_stream_set_pending (stream, &error))
837     {
838       g_task_return_error (task, error);
839       g_object_unref (task);
840       return;
841     }
842   
843   class = G_OUTPUT_STREAM_GET_CLASS (stream);
844
845   class->write_async (stream, buffer, count, io_priority, cancellable,
846                       async_ready_write_callback_wrapper, task);
847 }
848
849 /**
850  * g_output_stream_write_finish:
851  * @stream: a #GOutputStream.
852  * @result: a #GAsyncResult.
853  * @error: a #GError location to store the error occurring, or %NULL to 
854  * ignore.
855  * 
856  * Finishes a stream write operation.
857  * 
858  * Returns: a #gssize containing the number of bytes written to the stream.
859  **/
860 gssize
861 g_output_stream_write_finish (GOutputStream  *stream,
862                               GAsyncResult   *result,
863                               GError        **error)
864 {
865   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
866   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
867   g_return_val_if_fail (g_async_result_is_tagged (result, g_output_stream_write_async), FALSE);
868
869   /* @result is always the GTask created by g_output_stream_write_async();
870    * we called class->write_finish() from async_ready_write_callback_wrapper.
871    */
872   return g_task_propagate_int (G_TASK (result), error);
873 }
874
875 typedef struct
876 {
877   const guint8 *buffer;
878   gsize to_write;
879   gsize bytes_written;
880 } AsyncWriteAll;
881
882 static void
883 free_async_write_all (gpointer data)
884 {
885   g_slice_free (AsyncWriteAll, data);
886 }
887
888 static void
889 write_all_callback (GObject      *stream,
890                     GAsyncResult *result,
891                     gpointer      user_data)
892 {
893   GTask *task = user_data;
894   AsyncWriteAll *data = g_task_get_task_data (task);
895
896   if (result)
897     {
898       GError *error = NULL;
899       gssize nwritten;
900
901       nwritten = g_output_stream_write_finish (G_OUTPUT_STREAM (stream), result, &error);
902
903       if (nwritten == -1)
904         {
905           g_task_return_error (task, error);
906           g_object_unref (task);
907           return;
908         }
909
910       g_assert_cmpint (nwritten, <=, data->to_write);
911       g_warn_if_fail (nwritten > 0);
912
913       data->to_write -= nwritten;
914       data->bytes_written += nwritten;
915     }
916
917   if (data->to_write == 0)
918     {
919       g_task_return_boolean (task, TRUE);
920       g_object_unref (task);
921     }
922
923   else
924     g_output_stream_write_async (G_OUTPUT_STREAM (stream),
925                                  data->buffer + data->bytes_written,
926                                  data->to_write,
927                                  g_task_get_priority (task),
928                                  g_task_get_cancellable (task),
929                                  write_all_callback, task);
930 }
931
932 static void
933 write_all_async_thread (GTask        *task,
934                         gpointer      source_object,
935                         gpointer      task_data,
936                         GCancellable *cancellable)
937 {
938   GOutputStream *stream = source_object;
939   AsyncWriteAll *data = task_data;
940   GError *error = NULL;
941
942   if (g_output_stream_write_all (stream, data->buffer, data->to_write, &data->bytes_written,
943                                  g_task_get_cancellable (task), &error))
944     g_task_return_boolean (task, TRUE);
945   else
946     g_task_return_error (task, error);
947 }
948
949 /**
950  * g_output_stream_write_all_async:
951  * @stream: A #GOutputStream
952  * @buffer: (array length=count) (element-type guint8): the buffer containing the data to write
953  * @count: the number of bytes to write
954  * @io_priority: the io priority of the request
955  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore
956  * @callback: (scope async): callback to call when the request is satisfied
957  * @user_data: (closure): the data to pass to callback function
958  *
959  * Request an asynchronous write of @count bytes from @buffer into
960  * the stream. When the operation is finished @callback will be called.
961  * You can then call g_output_stream_write_all_finish() to get the result of the
962  * operation.
963  *
964  * This is the asynchronous version of g_output_stream_write_all().
965  *
966  * Call g_output_stream_write_all_finish() to collect the result.
967  *
968  * Any outstanding I/O request with higher priority (lower numerical
969  * value) will be executed before an outstanding request with lower
970  * priority. Default priority is %G_PRIORITY_DEFAULT.
971  *
972  * Note that no copy of @buffer will be made, so it must stay valid
973  * until @callback is called.
974  *
975  * Since: 2.44
976  */
977 void
978 g_output_stream_write_all_async (GOutputStream       *stream,
979                                  const void          *buffer,
980                                  gsize                count,
981                                  int                  io_priority,
982                                  GCancellable        *cancellable,
983                                  GAsyncReadyCallback  callback,
984                                  gpointer             user_data)
985 {
986   AsyncWriteAll *data;
987   GTask *task;
988
989   g_return_if_fail (G_IS_OUTPUT_STREAM (stream));
990   g_return_if_fail (buffer != NULL || count == 0);
991
992   task = g_task_new (stream, cancellable, callback, user_data);
993   data = g_slice_new0 (AsyncWriteAll);
994   data->buffer = buffer;
995   data->to_write = count;
996
997   g_task_set_task_data (task, data, free_async_write_all);
998   g_task_set_priority (task, io_priority);
999
1000   /* If async writes are going to be handled via the threadpool anyway
1001    * then we may as well do it with a single dispatch instead of
1002    * bouncing in and out.
1003    */
1004   if (g_output_stream_async_write_is_via_threads (stream))
1005     {
1006       g_task_run_in_thread (task, write_all_async_thread);
1007       g_object_unref (task);
1008     }
1009   else
1010     write_all_callback (G_OBJECT (stream), NULL, task);
1011 }
1012
1013 /**
1014  * g_output_stream_write_all_finish:
1015  * @stream: a #GOutputStream
1016  * @result: a #GAsyncResult
1017  * @bytes_written: (out): location to store the number of bytes that was written to the stream
1018  * @error: a #GError location to store the error occurring, or %NULL to ignore.
1019  *
1020  * Finishes an asynchronous stream write operation started with
1021  * g_output_stream_write_all_async().
1022  *
1023  * As a special exception to the normal conventions for functions that
1024  * use #GError, if this function returns %FALSE (and sets @error) then
1025  * @bytes_written will be set to the number of bytes that were
1026  * successfully written before the error was encountered.  This
1027  * functionality is only available from C.  If you need it from another
1028  * language then you must write your own loop around
1029  * g_output_stream_write_async().
1030  *
1031  * Returns: %TRUE on success, %FALSE if there was an error
1032  *
1033  * Since: 2.44
1034  **/
1035 gboolean
1036 g_output_stream_write_all_finish (GOutputStream  *stream,
1037                                   GAsyncResult   *result,
1038                                   gsize          *bytes_written,
1039                                   GError        **error)
1040 {
1041   GTask *task;
1042
1043   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
1044   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
1045
1046   task = G_TASK (result);
1047
1048   if (bytes_written)
1049     {
1050       AsyncWriteAll *data = (AsyncWriteAll *)g_task_get_task_data (task);
1051
1052       *bytes_written = data->bytes_written;
1053     }
1054
1055   return g_task_propagate_boolean (task, error);
1056 }
1057
1058 static void
1059 write_bytes_callback (GObject      *stream,
1060                       GAsyncResult *result,
1061                       gpointer      user_data)
1062 {
1063   GTask *task = user_data;
1064   GError *error = NULL;
1065   gssize nwrote;
1066
1067   nwrote = g_output_stream_write_finish (G_OUTPUT_STREAM (stream),
1068                                          result, &error);
1069   if (nwrote == -1)
1070     g_task_return_error (task, error);
1071   else
1072     g_task_return_int (task, nwrote);
1073   g_object_unref (task);
1074 }
1075
1076 /**
1077  * g_output_stream_write_bytes_async:
1078  * @stream: A #GOutputStream.
1079  * @bytes: The bytes to write
1080  * @io_priority: the io priority of the request.
1081  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
1082  * @callback: (scope async): callback to call when the request is satisfied
1083  * @user_data: (closure): the data to pass to callback function
1084  *
1085  * This function is similar to g_output_stream_write_async(), but
1086  * takes a #GBytes as input.  Due to the refcounted nature of #GBytes,
1087  * this allows the stream to avoid taking a copy of the data.
1088  *
1089  * However, note that this function may still perform partial writes,
1090  * just like g_output_stream_write_async(). If that occurs, to continue
1091  * writing, you will need to create a new #GBytes containing just the
1092  * remaining bytes, using g_bytes_new_from_bytes(). Passing the same
1093  * #GBytes instance multiple times potentially can result in duplicated
1094  * data in the output stream.
1095  *
1096  * For the synchronous, blocking version of this function, see
1097  * g_output_stream_write_bytes().
1098  **/
1099 void
1100 g_output_stream_write_bytes_async (GOutputStream       *stream,
1101                                    GBytes              *bytes,
1102                                    int                  io_priority,
1103                                    GCancellable        *cancellable,
1104                                    GAsyncReadyCallback  callback,
1105                                    gpointer             user_data)
1106 {
1107   GTask *task;
1108   gsize size;
1109   gconstpointer data;
1110
1111   data = g_bytes_get_data (bytes, &size);
1112
1113   task = g_task_new (stream, cancellable, callback, user_data);
1114   g_task_set_task_data (task, g_bytes_ref (bytes),
1115                         (GDestroyNotify) g_bytes_unref);
1116
1117   g_output_stream_write_async (stream,
1118                                data, size,
1119                                io_priority,
1120                                cancellable,
1121                                write_bytes_callback,
1122                                task);
1123 }
1124
1125 /**
1126  * g_output_stream_write_bytes_finish:
1127  * @stream: a #GOutputStream.
1128  * @result: a #GAsyncResult.
1129  * @error: a #GError location to store the error occurring, or %NULL to
1130  * ignore.
1131  *
1132  * Finishes a stream write-from-#GBytes operation.
1133  *
1134  * Returns: a #gssize containing the number of bytes written to the stream.
1135  **/
1136 gssize
1137 g_output_stream_write_bytes_finish (GOutputStream  *stream,
1138                                     GAsyncResult   *result,
1139                                     GError        **error)
1140 {
1141   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), -1);
1142   g_return_val_if_fail (g_task_is_valid (result, stream), -1);
1143
1144   return g_task_propagate_int (G_TASK (result), error);
1145 }
1146
1147 static void
1148 async_ready_splice_callback_wrapper (GObject      *source_object,
1149                                      GAsyncResult *res,
1150                                      gpointer     _data)
1151 {
1152   GOutputStream *stream = G_OUTPUT_STREAM (source_object);
1153   GOutputStreamClass *class;
1154   GTask *task = _data;
1155   gssize nspliced;
1156   GError *error = NULL;
1157
1158   g_output_stream_clear_pending (stream);
1159   
1160   if (g_async_result_legacy_propagate_error (res, &error))
1161     nspliced = -1;
1162   else
1163     {
1164       class = G_OUTPUT_STREAM_GET_CLASS (stream);
1165       nspliced = class->splice_finish (stream, res, &error);
1166     }
1167
1168   if (nspliced >= 0)
1169     g_task_return_int (task, nspliced);
1170   else
1171     g_task_return_error (task, error);
1172   g_object_unref (task);
1173 }
1174
1175 /**
1176  * g_output_stream_splice_async:
1177  * @stream: a #GOutputStream.
1178  * @source: a #GInputStream. 
1179  * @flags: a set of #GOutputStreamSpliceFlags.
1180  * @io_priority: the io priority of the request.
1181  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore. 
1182  * @callback: (scope async): a #GAsyncReadyCallback. 
1183  * @user_data: (closure): user data passed to @callback.
1184  * 
1185  * Splices a stream asynchronously.
1186  * When the operation is finished @callback will be called.
1187  * You can then call g_output_stream_splice_finish() to get the 
1188  * result of the operation.
1189  *
1190  * For the synchronous, blocking version of this function, see 
1191  * g_output_stream_splice().
1192  **/
1193 void
1194 g_output_stream_splice_async (GOutputStream            *stream,
1195                               GInputStream             *source,
1196                               GOutputStreamSpliceFlags  flags,
1197                               int                       io_priority,
1198                               GCancellable             *cancellable,
1199                               GAsyncReadyCallback       callback,
1200                               gpointer                  user_data)
1201 {
1202   GOutputStreamClass *class;
1203   GTask *task;
1204   GError *error = NULL;
1205
1206   g_return_if_fail (G_IS_OUTPUT_STREAM (stream));
1207   g_return_if_fail (G_IS_INPUT_STREAM (source));
1208
1209   task = g_task_new (stream, cancellable, callback, user_data);
1210   g_task_set_source_tag (task, g_output_stream_splice_async);
1211   g_task_set_priority (task, io_priority);
1212   g_task_set_task_data (task, g_object_ref (source), g_object_unref);
1213
1214   if (g_input_stream_is_closed (source))
1215     {
1216       g_task_return_new_error (task,
1217                                G_IO_ERROR, G_IO_ERROR_CLOSED,
1218                                _("Source stream is already closed"));
1219       g_object_unref (task);
1220       return;
1221     }
1222   
1223   if (!g_output_stream_set_pending (stream, &error))
1224     {
1225       g_task_return_error (task, error);
1226       g_object_unref (task);
1227       return;
1228     }
1229
1230   class = G_OUTPUT_STREAM_GET_CLASS (stream);
1231
1232   class->splice_async (stream, source, flags, io_priority, cancellable,
1233                        async_ready_splice_callback_wrapper, task);
1234 }
1235
1236 /**
1237  * g_output_stream_splice_finish:
1238  * @stream: a #GOutputStream.
1239  * @result: a #GAsyncResult.
1240  * @error: a #GError location to store the error occurring, or %NULL to 
1241  * ignore.
1242  *
1243  * Finishes an asynchronous stream splice operation.
1244  * 
1245  * Returns: a #gssize of the number of bytes spliced. Note that if the
1246  *     number of bytes spliced is greater than %G_MAXSSIZE, then that
1247  *     will be returned, and there is no way to determine the actual
1248  *     number of bytes spliced.
1249  **/
1250 gssize
1251 g_output_stream_splice_finish (GOutputStream  *stream,
1252                                GAsyncResult   *result,
1253                                GError        **error)
1254 {
1255   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
1256   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
1257   g_return_val_if_fail (g_async_result_is_tagged (result, g_output_stream_splice_async), FALSE);
1258
1259   /* @result is always the GTask created by g_output_stream_splice_async();
1260    * we called class->splice_finish() from async_ready_splice_callback_wrapper.
1261    */
1262   return g_task_propagate_int (G_TASK (result), error);
1263 }
1264
1265 static void
1266 async_ready_flush_callback_wrapper (GObject      *source_object,
1267                                     GAsyncResult *res,
1268                                     gpointer      user_data)
1269 {
1270   GOutputStream *stream = G_OUTPUT_STREAM (source_object);
1271   GOutputStreamClass *class;
1272   GTask *task = user_data;
1273   gboolean flushed;
1274   GError *error = NULL;
1275
1276   g_output_stream_clear_pending (stream);
1277   
1278   if (g_async_result_legacy_propagate_error (res, &error))
1279     flushed = FALSE;
1280   else
1281     {
1282       class = G_OUTPUT_STREAM_GET_CLASS (stream);
1283       flushed = class->flush_finish (stream, res, &error);
1284     }
1285
1286   if (flushed)
1287     g_task_return_boolean (task, TRUE);
1288   else
1289     g_task_return_error (task, error);
1290   g_object_unref (task);
1291 }
1292
1293 /**
1294  * g_output_stream_flush_async:
1295  * @stream: a #GOutputStream.
1296  * @io_priority: the io priority of the request.
1297  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
1298  * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied
1299  * @user_data: (closure): the data to pass to callback function
1300  * 
1301  * Forces an asynchronous write of all user-space buffered data for
1302  * the given @stream.
1303  * For behaviour details see g_output_stream_flush().
1304  *
1305  * When the operation is finished @callback will be 
1306  * called. You can then call g_output_stream_flush_finish() to get the 
1307  * result of the operation.
1308  **/
1309 void
1310 g_output_stream_flush_async (GOutputStream       *stream,
1311                              int                  io_priority,
1312                              GCancellable        *cancellable,
1313                              GAsyncReadyCallback  callback,
1314                              gpointer             user_data)
1315 {
1316   GOutputStreamClass *class;
1317   GTask *task;
1318   GError *error = NULL;
1319
1320   g_return_if_fail (G_IS_OUTPUT_STREAM (stream));
1321
1322   task = g_task_new (stream, cancellable, callback, user_data);
1323   g_task_set_source_tag (task, g_output_stream_flush_async);
1324   g_task_set_priority (task, io_priority);
1325
1326   if (!g_output_stream_set_pending (stream, &error))
1327     {
1328       g_task_return_error (task, error);
1329       g_object_unref (task);
1330       return;
1331     }
1332
1333   class = G_OUTPUT_STREAM_GET_CLASS (stream);
1334   
1335   if (class->flush_async == NULL)
1336     {
1337       g_task_return_boolean (task, TRUE);
1338       g_object_unref (task);
1339       return;
1340     }
1341       
1342   class->flush_async (stream, io_priority, cancellable,
1343                       async_ready_flush_callback_wrapper, task);
1344 }
1345
1346 /**
1347  * g_output_stream_flush_finish:
1348  * @stream: a #GOutputStream.
1349  * @result: a GAsyncResult.
1350  * @error: a #GError location to store the error occurring, or %NULL to 
1351  * ignore.
1352  * 
1353  * Finishes flushing an output stream.
1354  * 
1355  * Returns: %TRUE if flush operation succeeded, %FALSE otherwise.
1356  **/
1357 gboolean
1358 g_output_stream_flush_finish (GOutputStream  *stream,
1359                               GAsyncResult   *result,
1360                               GError        **error)
1361 {
1362   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
1363   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
1364   g_return_val_if_fail (g_async_result_is_tagged (result, g_output_stream_flush_async), FALSE);
1365
1366   /* @result is always the GTask created by g_output_stream_flush_async();
1367    * we called class->flush_finish() from async_ready_flush_callback_wrapper.
1368    */
1369   return g_task_propagate_boolean (G_TASK (result), error);
1370 }
1371
1372
1373 static void
1374 async_ready_close_callback_wrapper (GObject      *source_object,
1375                                     GAsyncResult *res,
1376                                     gpointer      user_data)
1377 {
1378   GOutputStream *stream = G_OUTPUT_STREAM (source_object);
1379   GOutputStreamClass *class;
1380   GTask *task = user_data;
1381   GError *error = g_task_get_task_data (task);
1382
1383   stream->priv->closing = FALSE;
1384   stream->priv->closed = TRUE;
1385
1386   if (!error && !g_async_result_legacy_propagate_error (res, &error))
1387     {
1388       class = G_OUTPUT_STREAM_GET_CLASS (stream);
1389
1390       class->close_finish (stream, res,
1391                            error ? NULL : &error);
1392     }
1393
1394   if (error != NULL)
1395     g_task_return_error (task, error);
1396   else
1397     g_task_return_boolean (task, TRUE);
1398   g_object_unref (task);
1399 }
1400
1401 static void
1402 async_ready_close_flushed_callback_wrapper (GObject      *source_object,
1403                                             GAsyncResult *res,
1404                                             gpointer      user_data)
1405 {
1406   GOutputStream *stream = G_OUTPUT_STREAM (source_object);
1407   GOutputStreamClass *class;
1408   GTask *task = user_data;
1409   GError *error = NULL;
1410
1411   class = G_OUTPUT_STREAM_GET_CLASS (stream);
1412
1413   if (!g_async_result_legacy_propagate_error (res, &error))
1414     {
1415       class->flush_finish (stream, res, &error);
1416     }
1417
1418   /* propagate the possible error */
1419   if (error)
1420     g_task_set_task_data (task, error, NULL);
1421
1422   /* we still close, even if there was a flush error */
1423   class->close_async (stream,
1424                       g_task_get_priority (task),
1425                       g_task_get_cancellable (task),
1426                       async_ready_close_callback_wrapper, task);
1427 }
1428
1429 static void
1430 real_close_async_cb (GObject      *source_object,
1431                      GAsyncResult *res,
1432                      gpointer      user_data)
1433 {
1434   GOutputStream *stream = G_OUTPUT_STREAM (source_object);
1435   GTask *task = user_data;
1436   GError *error = NULL;
1437   gboolean ret;
1438
1439   g_output_stream_clear_pending (stream);
1440
1441   ret = g_output_stream_internal_close_finish (stream, res, &error);
1442
1443   if (error != NULL)
1444     g_task_return_error (task, error);
1445   else
1446     g_task_return_boolean (task, ret);
1447
1448   g_object_unref (task);
1449 }
1450
1451 /**
1452  * g_output_stream_close_async:
1453  * @stream: A #GOutputStream.
1454  * @io_priority: the io priority of the request.
1455  * @cancellable: (allow-none): optional cancellable object
1456  * @callback: (scope async): callback to call when the request is satisfied
1457  * @user_data: (closure): the data to pass to callback function
1458  *
1459  * Requests an asynchronous close of the stream, releasing resources 
1460  * related to it. When the operation is finished @callback will be 
1461  * called. You can then call g_output_stream_close_finish() to get 
1462  * the result of the operation.
1463  *
1464  * For behaviour details see g_output_stream_close().
1465  *
1466  * The asyncronous methods have a default fallback that uses threads 
1467  * to implement asynchronicity, so they are optional for inheriting 
1468  * classes. However, if you override one you must override all.
1469  **/
1470 void
1471 g_output_stream_close_async (GOutputStream       *stream,
1472                              int                  io_priority,
1473                              GCancellable        *cancellable,
1474                              GAsyncReadyCallback  callback,
1475                              gpointer             user_data)
1476 {
1477   GTask *task;
1478   GError *error = NULL;
1479
1480   g_return_if_fail (G_IS_OUTPUT_STREAM (stream));
1481   
1482   task = g_task_new (stream, cancellable, callback, user_data);
1483   g_task_set_source_tag (task, g_output_stream_close_async);
1484   g_task_set_priority (task, io_priority);
1485
1486   if (!g_output_stream_set_pending (stream, &error))
1487     {
1488       g_task_return_error (task, error);
1489       g_object_unref (task);
1490       return;
1491     }
1492
1493   g_output_stream_internal_close_async (stream, io_priority, cancellable,
1494                                         real_close_async_cb, task);
1495 }
1496
1497 /* Must always be called inside
1498  * g_output_stream_set_pending()/g_output_stream_clear_pending().
1499  */
1500 void
1501 g_output_stream_internal_close_async (GOutputStream       *stream,
1502                                       int                  io_priority,
1503                                       GCancellable        *cancellable,
1504                                       GAsyncReadyCallback  callback,
1505                                       gpointer             user_data)
1506 {
1507   GOutputStreamClass *class;
1508   GTask *task;
1509
1510   task = g_task_new (stream, cancellable, callback, user_data);
1511   g_task_set_source_tag (task, g_output_stream_internal_close_async);
1512   g_task_set_priority (task, io_priority);
1513
1514   if (stream->priv->closed)
1515     {
1516       g_task_return_boolean (task, TRUE);
1517       g_object_unref (task);
1518       return;
1519     }
1520
1521   class = G_OUTPUT_STREAM_GET_CLASS (stream);
1522   stream->priv->closing = TRUE;
1523
1524   /* Call close_async directly if there is no need to flush, or if the flush
1525      can be done sync (in the output stream async close thread) */
1526   if (class->flush_async == NULL ||
1527       (class->flush_async == g_output_stream_real_flush_async &&
1528        (class->flush == NULL || class->close_async == g_output_stream_real_close_async)))
1529     {
1530       class->close_async (stream, io_priority, cancellable,
1531                           async_ready_close_callback_wrapper, task);
1532     }
1533   else
1534     {
1535       /* First do an async flush, then do the async close in the callback
1536          wrapper (see async_ready_close_flushed_callback_wrapper) */
1537       class->flush_async (stream, io_priority, cancellable,
1538                           async_ready_close_flushed_callback_wrapper, task);
1539     }
1540 }
1541
1542 static gboolean
1543 g_output_stream_internal_close_finish (GOutputStream  *stream,
1544                                        GAsyncResult   *result,
1545                                        GError        **error)
1546 {
1547   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
1548   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
1549   g_return_val_if_fail (g_async_result_is_tagged (result, g_output_stream_internal_close_async), FALSE);
1550
1551   return g_task_propagate_boolean (G_TASK (result), error);
1552 }
1553
1554 /**
1555  * g_output_stream_close_finish:
1556  * @stream: a #GOutputStream.
1557  * @result: a #GAsyncResult.
1558  * @error: a #GError location to store the error occurring, or %NULL to 
1559  * ignore.
1560  * 
1561  * Closes an output stream.
1562  * 
1563  * Returns: %TRUE if stream was successfully closed, %FALSE otherwise.
1564  **/
1565 gboolean
1566 g_output_stream_close_finish (GOutputStream  *stream,
1567                               GAsyncResult   *result,
1568                               GError        **error)
1569 {
1570   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
1571   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
1572   g_return_val_if_fail (g_async_result_is_tagged (result, g_output_stream_close_async), FALSE);
1573
1574   /* @result is always the GTask created by g_output_stream_close_async();
1575    * we called class->close_finish() from async_ready_close_callback_wrapper.
1576    */
1577   return g_task_propagate_boolean (G_TASK (result), error);
1578 }
1579
1580 /**
1581  * g_output_stream_is_closed:
1582  * @stream: a #GOutputStream.
1583  * 
1584  * Checks if an output stream has already been closed.
1585  * 
1586  * Returns: %TRUE if @stream is closed. %FALSE otherwise. 
1587  **/
1588 gboolean
1589 g_output_stream_is_closed (GOutputStream *stream)
1590 {
1591   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), TRUE);
1592   
1593   return stream->priv->closed;
1594 }
1595
1596 /**
1597  * g_output_stream_is_closing:
1598  * @stream: a #GOutputStream.
1599  *
1600  * Checks if an output stream is being closed. This can be
1601  * used inside e.g. a flush implementation to see if the
1602  * flush (or other i/o operation) is called from within
1603  * the closing operation.
1604  *
1605  * Returns: %TRUE if @stream is being closed. %FALSE otherwise.
1606  *
1607  * Since: 2.24
1608  **/
1609 gboolean
1610 g_output_stream_is_closing (GOutputStream *stream)
1611 {
1612   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), TRUE);
1613
1614   return stream->priv->closing;
1615 }
1616
1617 /**
1618  * g_output_stream_has_pending:
1619  * @stream: a #GOutputStream.
1620  * 
1621  * Checks if an ouput stream has pending actions.
1622  * 
1623  * Returns: %TRUE if @stream has pending actions. 
1624  **/
1625 gboolean
1626 g_output_stream_has_pending (GOutputStream *stream)
1627 {
1628   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
1629   
1630   return stream->priv->pending;
1631 }
1632
1633 /**
1634  * g_output_stream_set_pending:
1635  * @stream: a #GOutputStream.
1636  * @error: a #GError location to store the error occurring, or %NULL to 
1637  * ignore.
1638  * 
1639  * Sets @stream to have actions pending. If the pending flag is
1640  * already set or @stream is closed, it will return %FALSE and set
1641  * @error.
1642  *
1643  * Returns: %TRUE if pending was previously unset and is now set.
1644  **/
1645 gboolean
1646 g_output_stream_set_pending (GOutputStream *stream,
1647                              GError **error)
1648 {
1649   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
1650   
1651   if (stream->priv->closed)
1652     {
1653       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
1654                            _("Stream is already closed"));
1655       return FALSE;
1656     }
1657   
1658   if (stream->priv->pending)
1659     {
1660       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1661                            /* Translators: This is an error you get if there is
1662                             * already an operation running against this stream when
1663                             * you try to start one */
1664                            _("Stream has outstanding operation"));
1665       return FALSE;
1666     }
1667   
1668   stream->priv->pending = TRUE;
1669   return TRUE;
1670 }
1671
1672 /**
1673  * g_output_stream_clear_pending:
1674  * @stream: output stream
1675  * 
1676  * Clears the pending flag on @stream.
1677  **/
1678 void
1679 g_output_stream_clear_pending (GOutputStream *stream)
1680 {
1681   g_return_if_fail (G_IS_OUTPUT_STREAM (stream));
1682   
1683   stream->priv->pending = FALSE;
1684 }
1685
1686 /**
1687  * g_output_stream_async_write_is_via_threads:
1688  * @stream: a #GOutputStream.
1689  *
1690  * Checks if an ouput stream's write_async function uses threads.
1691  *
1692  * Returns: %TRUE if @stream's write_async function uses threads.
1693  **/
1694 gboolean
1695 g_output_stream_async_write_is_via_threads (GOutputStream *stream)
1696 {
1697   GOutputStreamClass *class;
1698
1699   g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
1700
1701   class = G_OUTPUT_STREAM_GET_CLASS (stream);
1702
1703   return (class->write_async == g_output_stream_real_write_async &&
1704       !(G_IS_POLLABLE_OUTPUT_STREAM (stream) &&
1705         g_pollable_output_stream_can_poll (G_POLLABLE_OUTPUT_STREAM (stream))));
1706 }
1707
1708
1709 /********************************************
1710  *   Default implementation of async ops    *
1711  ********************************************/
1712
1713 typedef struct {
1714   const void         *buffer;
1715   gsize               count_requested;
1716   gssize              count_written;
1717 } WriteData;
1718
1719 static void
1720 free_write_data (WriteData *op)
1721 {
1722   g_slice_free (WriteData, op);
1723 }
1724
1725 static void
1726 write_async_thread (GTask        *task,
1727                     gpointer      source_object,
1728                     gpointer      task_data,
1729                     GCancellable *cancellable)
1730 {
1731   GOutputStream *stream = source_object;
1732   WriteData *op = task_data;
1733   GOutputStreamClass *class;
1734   GError *error = NULL;
1735   gssize count_written;
1736
1737   class = G_OUTPUT_STREAM_GET_CLASS (stream);
1738   count_written = class->write_fn (stream, op->buffer, op->count_requested,
1739                                    cancellable, &error);
1740   if (count_written == -1)
1741     g_task_return_error (task, error);
1742   else
1743     g_task_return_int (task, count_written);
1744 }
1745
1746 static void write_async_pollable (GPollableOutputStream *stream,
1747                                   GTask                 *task);
1748
1749 static gboolean
1750 write_async_pollable_ready (GPollableOutputStream *stream,
1751                             gpointer               user_data)
1752 {
1753   GTask *task = user_data;
1754
1755   write_async_pollable (stream, task);
1756   return FALSE;
1757 }
1758
1759 static void
1760 write_async_pollable (GPollableOutputStream *stream,
1761                       GTask                 *task)
1762 {
1763   GError *error = NULL;
1764   WriteData *op = g_task_get_task_data (task);
1765   gssize count_written;
1766
1767   if (g_task_return_error_if_cancelled (task))
1768     return;
1769
1770   count_written = G_POLLABLE_OUTPUT_STREAM_GET_INTERFACE (stream)->
1771     write_nonblocking (stream, op->buffer, op->count_requested, &error);
1772
1773   if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1774     {
1775       GSource *source;
1776
1777       g_error_free (error);
1778
1779       source = g_pollable_output_stream_create_source (stream,
1780                                                        g_task_get_cancellable (task));
1781       g_task_attach_source (task, source,
1782                             (GSourceFunc) write_async_pollable_ready);
1783       g_source_unref (source);
1784       return;
1785     }
1786
1787   if (count_written == -1)
1788     g_task_return_error (task, error);
1789   else
1790     g_task_return_int (task, count_written);
1791 }
1792
1793 static void
1794 g_output_stream_real_write_async (GOutputStream       *stream,
1795                                   const void          *buffer,
1796                                   gsize                count,
1797                                   int                  io_priority,
1798                                   GCancellable        *cancellable,
1799                                   GAsyncReadyCallback  callback,
1800                                   gpointer             user_data)
1801 {
1802   GTask *task;
1803   WriteData *op;
1804
1805   op = g_slice_new0 (WriteData);
1806   task = g_task_new (stream, cancellable, callback, user_data);
1807   g_task_set_check_cancellable (task, FALSE);
1808   g_task_set_task_data (task, op, (GDestroyNotify) free_write_data);
1809   op->buffer = buffer;
1810   op->count_requested = count;
1811
1812   if (!g_output_stream_async_write_is_via_threads (stream))
1813     write_async_pollable (G_POLLABLE_OUTPUT_STREAM (stream), task);
1814   else
1815     g_task_run_in_thread (task, write_async_thread);
1816   g_object_unref (task);
1817 }
1818
1819 static gssize
1820 g_output_stream_real_write_finish (GOutputStream  *stream,
1821                                    GAsyncResult   *result,
1822                                    GError        **error)
1823 {
1824   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
1825
1826   return g_task_propagate_int (G_TASK (result), error);
1827 }
1828
1829 typedef struct {
1830   GInputStream *source;
1831   GOutputStreamSpliceFlags flags;
1832   gssize n_read;
1833   gssize n_written;
1834   gsize bytes_copied;
1835   GError *error;
1836   guint8 *buffer;
1837 } SpliceData;
1838
1839 static void
1840 free_splice_data (SpliceData *op)
1841 {
1842   g_clear_pointer (&op->buffer, g_free);
1843   g_object_unref (op->source);
1844   g_clear_error (&op->error);
1845   g_free (op);
1846 }
1847
1848 static void
1849 real_splice_async_complete_cb (GTask *task)
1850 {
1851   SpliceData *op = g_task_get_task_data (task);
1852
1853   if (op->flags & G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE &&
1854       !g_input_stream_is_closed (op->source))
1855     return;
1856
1857   if (op->flags & G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET &&
1858       !g_output_stream_is_closed (g_task_get_source_object (task)))
1859     return;
1860
1861   if (op->error != NULL)
1862     {
1863       g_task_return_error (task, op->error);
1864       op->error = NULL;
1865     }
1866   else
1867     {
1868       g_task_return_int (task, op->bytes_copied);
1869     }
1870
1871   g_object_unref (task);
1872 }
1873
1874 static void
1875 real_splice_async_close_input_cb (GObject      *source,
1876                                   GAsyncResult *res,
1877                                   gpointer      user_data)
1878 {
1879   GTask *task = user_data;
1880
1881   g_input_stream_close_finish (G_INPUT_STREAM (source), res, NULL);
1882
1883   real_splice_async_complete_cb (task);
1884 }
1885
1886 static void
1887 real_splice_async_close_output_cb (GObject      *source,
1888                                    GAsyncResult *res,
1889                                    gpointer      user_data)
1890 {
1891   GTask *task = G_TASK (user_data);
1892   SpliceData *op = g_task_get_task_data (task);
1893   GError **error = (op->error == NULL) ? &op->error : NULL;
1894
1895   g_output_stream_internal_close_finish (G_OUTPUT_STREAM (source), res, error);
1896
1897   real_splice_async_complete_cb (task);
1898 }
1899
1900 static void
1901 real_splice_async_complete (GTask *task)
1902 {
1903   SpliceData *op = g_task_get_task_data (task);
1904   gboolean done = TRUE;
1905
1906   if (op->flags & G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE)
1907     {
1908       done = FALSE;
1909       g_input_stream_close_async (op->source, g_task_get_priority (task),
1910                                   g_task_get_cancellable (task),
1911                                   real_splice_async_close_input_cb, task);
1912     }
1913
1914   if (op->flags & G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET)
1915     {
1916       done = FALSE;
1917       g_output_stream_internal_close_async (g_task_get_source_object (task),
1918                                             g_task_get_priority (task),
1919                                             g_task_get_cancellable (task),
1920                                             real_splice_async_close_output_cb,
1921                                             task);
1922     }
1923
1924   if (done)
1925     real_splice_async_complete_cb (task);
1926 }
1927
1928 static void real_splice_async_read_cb (GObject      *source,
1929                                        GAsyncResult *res,
1930                                        gpointer      user_data);
1931
1932 static void
1933 real_splice_async_write_cb (GObject      *source,
1934                             GAsyncResult *res,
1935                             gpointer      user_data)
1936 {
1937   GOutputStreamClass *class;
1938   GTask *task = G_TASK (user_data);
1939   SpliceData *op = g_task_get_task_data (task);
1940   gssize ret;
1941
1942   class = G_OUTPUT_STREAM_GET_CLASS (g_task_get_source_object (task));
1943
1944   ret = class->write_finish (G_OUTPUT_STREAM (source), res, &op->error);
1945
1946   if (ret == -1)
1947     {
1948       real_splice_async_complete (task);
1949       return;
1950     }
1951
1952   op->n_written += ret;
1953   op->bytes_copied += ret;
1954   if (op->bytes_copied > G_MAXSSIZE)
1955     op->bytes_copied = G_MAXSSIZE;
1956
1957   if (op->n_written < op->n_read)
1958     {
1959       class->write_async (g_task_get_source_object (task),
1960                           op->buffer + op->n_written,
1961                           op->n_read - op->n_written,
1962                           g_task_get_priority (task),
1963                           g_task_get_cancellable (task),
1964                           real_splice_async_write_cb, task);
1965       return;
1966     }
1967
1968   g_input_stream_read_async (op->source, op->buffer, 8192,
1969                              g_task_get_priority (task),
1970                              g_task_get_cancellable (task),
1971                              real_splice_async_read_cb, task);
1972 }
1973
1974 static void
1975 real_splice_async_read_cb (GObject      *source,
1976                            GAsyncResult *res,
1977                            gpointer      user_data)
1978 {
1979   GOutputStreamClass *class;
1980   GTask *task = G_TASK (user_data);
1981   SpliceData *op = g_task_get_task_data (task);
1982   gssize ret;
1983
1984   class = G_OUTPUT_STREAM_GET_CLASS (g_task_get_source_object (task));
1985
1986   ret = g_input_stream_read_finish (op->source, res, &op->error);
1987   if (ret == -1 || ret == 0)
1988     {
1989       real_splice_async_complete (task);
1990       return;
1991     }
1992
1993   op->n_read = ret;
1994   op->n_written = 0;
1995
1996   class->write_async (g_task_get_source_object (task), op->buffer,
1997                       op->n_read, g_task_get_priority (task),
1998                       g_task_get_cancellable (task),
1999                       real_splice_async_write_cb, task);
2000 }
2001
2002 static void
2003 splice_async_thread (GTask        *task,
2004                      gpointer      source_object,
2005                      gpointer      task_data,
2006                      GCancellable *cancellable)
2007 {
2008   GOutputStream *stream = source_object;
2009   SpliceData *op = task_data;
2010   GOutputStreamClass *class;
2011   GError *error = NULL;
2012   gssize bytes_copied;
2013
2014   class = G_OUTPUT_STREAM_GET_CLASS (stream);
2015   
2016   bytes_copied = class->splice (stream,
2017                                 op->source,
2018                                 op->flags,
2019                                 cancellable,
2020                                 &error);
2021   if (bytes_copied == -1)
2022     g_task_return_error (task, error);
2023   else
2024     g_task_return_int (task, bytes_copied);
2025 }
2026
2027 static void
2028 g_output_stream_real_splice_async (GOutputStream             *stream,
2029                                    GInputStream              *source,
2030                                    GOutputStreamSpliceFlags   flags,
2031                                    int                        io_priority,
2032                                    GCancellable              *cancellable,
2033                                    GAsyncReadyCallback        callback,
2034                                    gpointer                   user_data)
2035 {
2036   GTask *task;
2037   SpliceData *op;
2038
2039   op = g_new0 (SpliceData, 1);
2040   task = g_task_new (stream, cancellable, callback, user_data);
2041   g_task_set_task_data (task, op, (GDestroyNotify)free_splice_data);
2042   op->flags = flags;
2043   op->source = g_object_ref (source);
2044
2045   if (g_input_stream_async_read_is_via_threads (source) &&
2046       g_output_stream_async_write_is_via_threads (stream))
2047     {
2048       g_task_run_in_thread (task, splice_async_thread);
2049       g_object_unref (task);
2050     }
2051   else
2052     {
2053       op->buffer = g_malloc (8192);
2054       g_input_stream_read_async (op->source, op->buffer, 8192,
2055                                  g_task_get_priority (task),
2056                                  g_task_get_cancellable (task),
2057                                  real_splice_async_read_cb, task);
2058     }
2059 }
2060
2061 static gssize
2062 g_output_stream_real_splice_finish (GOutputStream  *stream,
2063                                     GAsyncResult   *result,
2064                                     GError        **error)
2065 {
2066   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
2067
2068   return g_task_propagate_int (G_TASK (result), error);
2069 }
2070
2071
2072 static void
2073 flush_async_thread (GTask        *task,
2074                     gpointer      source_object,
2075                     gpointer      task_data,
2076                     GCancellable *cancellable)
2077 {
2078   GOutputStream *stream = source_object;
2079   GOutputStreamClass *class;
2080   gboolean result;
2081   GError *error = NULL;
2082
2083   class = G_OUTPUT_STREAM_GET_CLASS (stream);
2084   result = TRUE;
2085   if (class->flush)
2086     result = class->flush (stream, cancellable, &error);
2087
2088   if (result)
2089     g_task_return_boolean (task, TRUE);
2090   else
2091     g_task_return_error (task, error);
2092 }
2093
2094 static void
2095 g_output_stream_real_flush_async (GOutputStream       *stream,
2096                                   int                  io_priority,
2097                                   GCancellable        *cancellable,
2098                                   GAsyncReadyCallback  callback,
2099                                   gpointer             user_data)
2100 {
2101   GTask *task;
2102
2103   task = g_task_new (stream, cancellable, callback, user_data);
2104   g_task_set_priority (task, io_priority);
2105   g_task_run_in_thread (task, flush_async_thread);
2106   g_object_unref (task);
2107 }
2108
2109 static gboolean
2110 g_output_stream_real_flush_finish (GOutputStream  *stream,
2111                                    GAsyncResult   *result,
2112                                    GError        **error)
2113 {
2114   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
2115
2116   return g_task_propagate_boolean (G_TASK (result), error);
2117 }
2118
2119 static void
2120 close_async_thread (GTask        *task,
2121                     gpointer      source_object,
2122                     gpointer      task_data,
2123                     GCancellable *cancellable)
2124 {
2125   GOutputStream *stream = source_object;
2126   GOutputStreamClass *class;
2127   GError *error = NULL;
2128   gboolean result = TRUE;
2129
2130   class = G_OUTPUT_STREAM_GET_CLASS (stream);
2131
2132   /* Do a flush here if there is a flush function, and we did not have to do
2133    * an async flush before (see g_output_stream_close_async)
2134    */
2135   if (class->flush != NULL &&
2136       (class->flush_async == NULL ||
2137        class->flush_async == g_output_stream_real_flush_async))
2138     {
2139       result = class->flush (stream, cancellable, &error);
2140     }
2141
2142   /* Auto handling of cancelation disabled, and ignore
2143      cancellation, since we want to close things anyway, although
2144      possibly in a quick-n-dirty way. At least we never want to leak
2145      open handles */
2146
2147   if (class->close_fn)
2148     {
2149       /* Make sure to close, even if the flush failed (see sync close) */
2150       if (!result)
2151         class->close_fn (stream, cancellable, NULL);
2152       else
2153         result = class->close_fn (stream, cancellable, &error);
2154     }
2155
2156   if (result)
2157     g_task_return_boolean (task, TRUE);
2158   else
2159     g_task_return_error (task, error);
2160 }
2161
2162 static void
2163 g_output_stream_real_close_async (GOutputStream       *stream,
2164                                   int                  io_priority,
2165                                   GCancellable        *cancellable,
2166                                   GAsyncReadyCallback  callback,
2167                                   gpointer             user_data)
2168 {
2169   GTask *task;
2170
2171   task = g_task_new (stream, cancellable, callback, user_data);
2172   g_task_set_priority (task, io_priority);
2173   g_task_run_in_thread (task, close_async_thread);
2174   g_object_unref (task);
2175 }
2176
2177 static gboolean
2178 g_output_stream_real_close_finish (GOutputStream  *stream,
2179                                    GAsyncResult   *result,
2180                                    GError        **error)
2181 {
2182   g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
2183
2184   return g_task_propagate_boolean (G_TASK (result), error);
2185 }