Corrected some typos in the documentation: occured -> occurred. its ->
[platform/upstream/glib.git] / gio / ginputstream.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include <config.h>
24 #include <glib.h>
25 #include "glibintl.h"
26
27 #include "ginputstream.h"
28 #include "gseekable.h"
29 #include "gsimpleasyncresult.h"
30
31 #include "gioalias.h"
32
33 /**
34  * SECTION:ginputstream
35  * @short_description: Base class for implementing streaming input
36  * @include: gio.h
37  *
38  * 
39  * 
40  **/
41
42 G_DEFINE_TYPE (GInputStream, g_input_stream, G_TYPE_OBJECT);
43
44 struct _GInputStreamPrivate {
45   guint closed : 1;
46   guint pending : 1;
47   GAsyncReadyCallback outstanding_callback;
48 };
49
50 static gssize   g_input_stream_real_skip         (GInputStream         *stream,
51                                                   gsize                 count,
52                                                   GCancellable         *cancellable,
53                                                   GError              **error);
54 static void     g_input_stream_real_read_async   (GInputStream         *stream,
55                                                   void                 *buffer,
56                                                   gsize                 count,
57                                                   int                   io_priority,
58                                                   GCancellable         *cancellable,
59                                                   GAsyncReadyCallback   callback,
60                                                   gpointer              user_data);
61 static gssize   g_input_stream_real_read_finish  (GInputStream         *stream,
62                                                   GAsyncResult         *result,
63                                                   GError              **error);
64 static void     g_input_stream_real_skip_async   (GInputStream         *stream,
65                                                   gsize                 count,
66                                                   int                   io_priority,
67                                                   GCancellable         *cancellable,
68                                                   GAsyncReadyCallback   callback,
69                                                   gpointer              data);
70 static gssize   g_input_stream_real_skip_finish  (GInputStream         *stream,
71                                                   GAsyncResult         *result,
72                                                   GError              **error);
73 static void     g_input_stream_real_close_async  (GInputStream         *stream,
74                                                   int                   io_priority,
75                                                   GCancellable         *cancellable,
76                                                   GAsyncReadyCallback   callback,
77                                                   gpointer              data);
78 static gboolean g_input_stream_real_close_finish (GInputStream         *stream,
79                                                   GAsyncResult         *result,
80                                                   GError              **error);
81
82 static void
83 g_input_stream_finalize (GObject *object)
84 {
85   GInputStream *stream;
86
87   stream = G_INPUT_STREAM (object);
88   
89   if (!stream->priv->closed)
90     g_input_stream_close (stream, NULL, NULL);
91
92   if (G_OBJECT_CLASS (g_input_stream_parent_class)->finalize)
93     (*G_OBJECT_CLASS (g_input_stream_parent_class)->finalize) (object);
94 }
95
96 static void
97 g_input_stream_dispose (GObject *object)
98 {
99   GInputStream *stream;
100
101   stream = G_INPUT_STREAM (object);
102   
103   if (!stream->priv->closed)
104     g_input_stream_close (stream, NULL, NULL);
105   
106   if (G_OBJECT_CLASS (g_input_stream_parent_class)->dispose)
107     (*G_OBJECT_CLASS (g_input_stream_parent_class)->dispose) (object);
108 }
109
110
111 static void
112 g_input_stream_class_init (GInputStreamClass *klass)
113 {
114   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
115   
116   g_type_class_add_private (klass, sizeof (GInputStreamPrivate));
117   
118   gobject_class->finalize = g_input_stream_finalize;
119   gobject_class->dispose = g_input_stream_dispose;
120   
121   klass->skip = g_input_stream_real_skip;
122   klass->read_async = g_input_stream_real_read_async;
123   klass->read_finish = g_input_stream_real_read_finish;
124   klass->skip_async = g_input_stream_real_skip_async;
125   klass->skip_finish = g_input_stream_real_skip_finish;
126   klass->close_async = g_input_stream_real_close_async;
127   klass->close_finish = g_input_stream_real_close_finish;
128 }
129
130 static void
131 g_input_stream_init (GInputStream *stream)
132 {
133   stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (stream,
134                                               G_TYPE_INPUT_STREAM,
135                                               GInputStreamPrivate);
136 }
137
138 /**
139  * g_input_stream_read:
140  * @stream: a #GInputStream.
141  * @buffer: a buffer to read data into (which should be at least count bytes long).
142  * @count: the number of bytes that will be read from the stream
143  * @cancellable: optional #GCancellable object, %NULL to ignore.
144  * @error: location to store the error occuring, or %NULL to ignore
145  *
146  * Tries to read @count bytes from the stream into the buffer starting at
147  * @buffer. Will block during this read.
148  * 
149  * If count is zero returns zero and does nothing. A value of @count
150  * larger than %G_MAXSSIZE will cause a %G_IO_ERROR_INVALID_ARGUMENT error.
151  *
152  * On success, the number of bytes read into the buffer is returned.
153  * It is not an error if this is not the same as the requested size, as it
154  * can happen e.g. near the end of a file. Zero is returned on end of file
155  * (or if @count is zero),  but never otherwise.
156  *
157  * If @cancellable is not NULL, then the operation can be cancelled by
158  * triggering the cancellable object from another thread. If the operation
159  * was cancelled, the error G_IO_ERROR_CANCELLED will be returned. If an
160  * operation was partially finished when the operation was cancelled the
161  * partial result will be returned, without an error.
162  *
163  * On error -1 is returned and @error is set accordingly.
164  * 
165  * Return value: Number of bytes read, or -1 on error
166  **/
167 gssize
168 g_input_stream_read  (GInputStream  *stream,
169                       void          *buffer,
170                       gsize          count,
171                       GCancellable  *cancellable,
172                       GError       **error)
173 {
174   GInputStreamClass *class;
175   gssize res;
176
177   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), -1);
178   g_return_val_if_fail (buffer != NULL, 0);
179
180   if (count == 0)
181     return 0;
182   
183   if (((gssize) count) < 0)
184     {
185       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
186                    _("Too large count value passed to g_input_stream_read"));
187       return -1;
188     }
189
190   class = G_INPUT_STREAM_GET_CLASS (stream);
191
192   if (class->read_fn == NULL) 
193     {
194       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
195                    _("Input stream doesn't implement read"));
196       return -1;
197     }
198
199   if (!g_input_stream_set_pending (stream, error))
200     return -1;
201
202   if (cancellable)
203     g_cancellable_push_current (cancellable);
204   
205   res = class->read_fn (stream, buffer, count, cancellable, error);
206
207   if (cancellable)
208     g_cancellable_pop_current (cancellable);
209   
210   g_input_stream_clear_pending (stream);
211
212   return res;
213 }
214
215 /**
216  * g_input_stream_read_all:
217  * @stream: a #GInputStream.
218  * @buffer: a buffer to read data into (which should be at least count bytes long).
219  * @count: the number of bytes that will be read from the stream
220  * @bytes_read: location to store the number of bytes that was read from the stream
221  * @cancellable: optional #GCancellable object, %NULL to ignore.
222  * @error: location to store the error occuring, or %NULL to ignore
223  *
224  * Tries to read @count bytes from the stream into the buffer starting at
225  * @buffer. Will block during this read.
226  *
227  * This function is similar to g_input_stream_read(), except it tries to
228  * read as many bytes as requested, only stopping on an error or end of stream.
229  *
230  * On a successful read of @count bytes, or if we reached the end of the
231  * stream,  %TRUE is returned, and @bytes_read is set to the number of bytes
232  * read into @buffer.
233  * 
234  * If there is an error during the operation %FALSE is returned and @error
235  * is set to indicate the error status, @bytes_read is updated to contain
236  * the number of bytes read into @buffer before the error occurred.
237  *
238  * Return value: %TRUE on success, %FALSE if there was an error
239  **/
240 gboolean
241 g_input_stream_read_all (GInputStream  *stream,
242                          void          *buffer,
243                          gsize          count,
244                          gsize         *bytes_read,
245                          GCancellable  *cancellable,
246                          GError       **error)
247 {
248   gsize _bytes_read;
249   gssize res;
250
251   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), FALSE);
252   g_return_val_if_fail (buffer != NULL, FALSE);
253
254   _bytes_read = 0;
255   while (_bytes_read < count)
256     {
257       res = g_input_stream_read (stream, (char *)buffer + _bytes_read, count - _bytes_read,
258                                  cancellable, error);
259       if (res == -1)
260         {
261           if (bytes_read)
262             *bytes_read = _bytes_read;
263           return FALSE;
264         }
265       
266       if (res == 0)
267         break;
268
269       _bytes_read += res;
270     }
271
272   if (bytes_read)
273     *bytes_read = _bytes_read;
274   return TRUE;
275 }
276
277 /**
278  * g_input_stream_skip:
279  * @stream: a #GInputStream.
280  * @count: the number of bytes that will be skipped from the stream
281  * @cancellable: optional #GCancellable object, %NULL to ignore. 
282  * @error: location to store the error occuring, or %NULL to ignore
283  *
284  * Tries to skip @count bytes from the stream. Will block during the operation.
285  *
286  * This is identical to g_input_stream_read(), from a behaviour standpoint,
287  * but the bytes that are skipped are not returned to the user. Some
288  * streams have an implementation that is more efficient than reading the data.
289  *
290  * This function is optional for inherited classes, as the default implementation
291  * emulates it using read.
292  *
293  * If @cancellable is not %NULL, then the operation can be cancelled by
294  * triggering the cancellable object from another thread. If the operation
295  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. If an
296  * operation was partially finished when the operation was cancelled the
297  * partial result will be returned, without an error.
298  *
299  * Return value: Number of bytes skipped, or -1 on error
300  **/
301 gssize
302 g_input_stream_skip (GInputStream  *stream,
303                      gsize          count,
304                      GCancellable  *cancellable,
305                      GError       **error)
306 {
307   GInputStreamClass *class;
308   gssize res;
309
310   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), -1);
311
312   if (count == 0)
313     return 0;
314
315   if (((gssize) count) < 0)
316     {
317       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
318                    _("Too large count value passed to g_input_stream_skip"));
319       return -1;
320     }
321   
322   class = G_INPUT_STREAM_GET_CLASS (stream);
323
324   if (!g_input_stream_set_pending (stream, error))
325     return -1;
326
327   if (cancellable)
328     g_cancellable_push_current (cancellable);
329   
330   res = class->skip (stream, count, cancellable, error);
331
332   if (cancellable)
333     g_cancellable_pop_current (cancellable);
334   
335   g_input_stream_clear_pending (stream);
336
337   return res;
338 }
339
340 static gssize
341 g_input_stream_real_skip (GInputStream  *stream,
342                           gsize          count,
343                           GCancellable  *cancellable,
344                           GError       **error)
345 {
346   GInputStreamClass *class;
347   gssize ret, read_bytes;
348   char buffer[8192];
349   GError *my_error;
350
351   class = G_INPUT_STREAM_GET_CLASS (stream);
352
353   if (G_IS_SEEKABLE (stream) && g_seekable_can_seek (G_SEEKABLE (stream)))
354     {
355       if (g_seekable_seek (G_SEEKABLE (stream),
356                            count,
357                            G_SEEK_CUR,
358                            cancellable,
359                            NULL))
360         return count;
361     }
362
363   /* If not seekable, or seek failed, fall back to reading data: */
364
365   class = G_INPUT_STREAM_GET_CLASS (stream);
366   
367   read_bytes = 0;
368   while (1)
369     {
370       my_error = NULL;
371
372       ret = class->read_fn (stream, buffer, MIN (sizeof (buffer), count),
373                          cancellable, &my_error);
374       if (ret == -1)
375         {
376           if (read_bytes > 0 &&
377               my_error->domain == G_IO_ERROR &&
378               my_error->code == G_IO_ERROR_CANCELLED)
379             {
380               g_error_free (my_error);
381               return read_bytes;
382             }
383           
384           g_propagate_error (error, my_error);
385           return -1;
386         }
387
388       count -= ret;
389       read_bytes += ret;
390       
391       if (ret == 0 || count == 0)
392         return read_bytes;
393     }
394 }
395
396 /**
397  * g_input_stream_close:
398  * @stream: A #GInputStream.
399  * @cancellable: optional #GCancellable object, %NULL to ignore.
400  * @error: location to store the error occuring, or %NULL to ignore
401  *
402  * Closes the stream, releasing resources related to it.
403  *
404  * Once the stream is closed, all other operations will return %G_IO_ERROR_CLOSED.
405  * Closing a stream multiple times will not return an error.
406  *
407  * Streams will be automatically closed when the last reference
408  * is dropped, but you might want to call make sure resources
409  * are released as early as possible.
410  *
411  * Some streams might keep the backing store of the stream (e.g. a file descriptor)
412  * open after the stream is closed. See the documentation for the individual
413  * stream for details.
414  *
415  * On failure the first error that happened will be reported, but the close
416  * operation will finish as much as possible. A stream that failed to
417  * close will still return %G_IO_ERROR_CLOSED all operations. Still, it
418  * is important to check and report the error to the user.
419  *
420  * If @cancellable is not NULL, then the operation can be cancelled by
421  * triggering the cancellable object from another thread. If the operation
422  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
423  * Cancelling a close will still leave the stream closed, but some streams
424  * can use a faster close that doesn't block to e.g. check errors. 
425  *
426  * Return value: %TRUE on success, %FALSE on failure
427  **/
428 gboolean
429 g_input_stream_close (GInputStream  *stream,
430                       GCancellable  *cancellable,
431                       GError       **error)
432 {
433   GInputStreamClass *class;
434   gboolean res;
435
436   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), FALSE);
437
438   class = G_INPUT_STREAM_GET_CLASS (stream);
439
440   if (stream->priv->closed)
441     return TRUE;
442
443   res = TRUE;
444
445   if (!g_input_stream_set_pending (stream, error))
446     return FALSE;
447
448   if (cancellable)
449     g_cancellable_push_current (cancellable);
450
451   if (class->close_fn)
452     res = class->close_fn (stream, cancellable, error);
453
454   if (cancellable)
455     g_cancellable_pop_current (cancellable);
456
457   g_input_stream_clear_pending (stream);
458   
459   stream->priv->closed = TRUE;
460   
461   return res;
462 }
463
464 static void
465 async_ready_callback_wrapper (GObject      *source_object,
466                               GAsyncResult *res,
467                               gpointer      user_data)
468 {
469   GInputStream *stream = G_INPUT_STREAM (source_object);
470
471   g_input_stream_clear_pending (stream);
472   if (stream->priv->outstanding_callback)
473     (*stream->priv->outstanding_callback) (source_object, res, user_data);
474   g_object_unref (stream);
475 }
476
477 static void
478 async_ready_close_callback_wrapper (GObject      *source_object,
479                                     GAsyncResult *res,
480                                     gpointer      user_data)
481 {
482   GInputStream *stream = G_INPUT_STREAM (source_object);
483
484   g_input_stream_clear_pending (stream);
485   stream->priv->closed = TRUE;
486   if (stream->priv->outstanding_callback)
487     (*stream->priv->outstanding_callback) (source_object, res, user_data);
488   g_object_unref (stream);
489 }
490
491 /**
492  * g_input_stream_read_async:
493  * @stream: A #GInputStream.
494  * @buffer: a buffer to read data into (which should be at least count bytes long).
495  * @count: the number of bytes that will be read from the stream
496  * @io_priority: the <link linkend="io-priority">I/O priority</link> 
497  * of the request. 
498  * @cancellable: optional #GCancellable object, %NULL to ignore.
499  * @callback: callback to call when the request is satisfied
500  * @user_data: the data to pass to callback function
501  *
502  * Request an asynchronous read of @count bytes from the stream into the buffer
503  * starting at @buffer. When the operation is finished @callback will be called,
504  * giving the results.
505  *
506  * During an async request no other sync and async calls are allowed, and will
507  * result in %G_IO_ERROR_PENDING errors. 
508  *
509  * A value of @count larger than %G_MAXSSIZE will cause a %G_IO_ERROR_INVALID_ARGUMENT error.
510  *
511  * On success, the number of bytes read into the buffer will be passed to the
512  * callback. It is not an error if this is not the same as the requested size, as it
513  * can happen e.g. near the end of a file, but generally we try to read
514  * as many bytes as requested. Zero is returned on end of file
515  * (or if @count is zero),  but never otherwise.
516  *
517  * Any outstanding i/o request with higher priority (lower numerical value) will
518  * be executed before an outstanding request with lower priority. Default
519  * priority is %G_PRIORITY_DEFAULT.
520  *
521  * The asyncronous methods have a default fallback that uses threads to implement
522  * asynchronicity, so they are optional for inheriting classes. However, if you
523  * override one you must override all.
524  **/
525 void
526 g_input_stream_read_async (GInputStream        *stream,
527                            void                *buffer,
528                            gsize                count,
529                            int                  io_priority,
530                            GCancellable        *cancellable,
531                            GAsyncReadyCallback  callback,
532                            gpointer             user_data)
533 {
534   GInputStreamClass *class;
535   GSimpleAsyncResult *simple;
536   GError *error = NULL;
537
538   g_return_if_fail (G_IS_INPUT_STREAM (stream));
539   g_return_if_fail (buffer != NULL);
540
541   if (count == 0)
542     {
543       simple = g_simple_async_result_new (G_OBJECT (stream),
544                                           callback,
545                                           user_data,
546                                           g_input_stream_read_async);
547       g_simple_async_result_complete_in_idle (simple);
548       g_object_unref (simple);
549       return;
550     }
551   
552   if (((gssize) count) < 0)
553     {
554       g_simple_async_report_error_in_idle (G_OBJECT (stream),
555                                            callback,
556                                            user_data,
557                                            G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
558                                            _("Too large count value passed to g_input_stream_read_async"));
559       return;
560     }
561
562   if (!g_input_stream_set_pending (stream, &error))
563     {
564       g_simple_async_report_gerror_in_idle (G_OBJECT (stream),
565                                             callback,
566                                             user_data,
567                                             error);
568       g_error_free (error);
569       return;
570     }
571
572   class = G_INPUT_STREAM_GET_CLASS (stream);
573   stream->priv->outstanding_callback = callback;
574   g_object_ref (stream);
575   class->read_async (stream, buffer, count, io_priority, cancellable,
576                      async_ready_callback_wrapper, user_data);
577 }
578
579 /**
580  * g_input_stream_read_finish:
581  * @stream: a #GInputStream.
582  * @result: a #GAsyncResult.
583  * @error: a #GError location to store the error occuring, or %NULL to 
584  * ignore.
585  * 
586  * Finishes an asynchronous stream read operation. 
587  * 
588  * Returns: number of bytes read in, or -1 on error.
589  **/
590 gssize
591 g_input_stream_read_finish (GInputStream  *stream,
592                             GAsyncResult  *result,
593                             GError       **error)
594 {
595   GSimpleAsyncResult *simple;
596   GInputStreamClass *class;
597   
598   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), -1);
599   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), -1);
600
601   if (G_IS_SIMPLE_ASYNC_RESULT (result))
602     {
603       simple = G_SIMPLE_ASYNC_RESULT (result);
604       if (g_simple_async_result_propagate_error (simple, error))
605         return -1;
606
607       /* Special case read of 0 bytes */
608       if (g_simple_async_result_get_source_tag (simple) == g_input_stream_read_async)
609         return 0;
610     }
611
612   class = G_INPUT_STREAM_GET_CLASS (stream);
613   return class->read_finish (stream, result, error);
614 }
615
616 /**
617  * g_input_stream_skip_async:
618  * @stream: A #GInputStream.
619  * @count: the number of bytes that will be skipped from the stream
620  * @io_priority: the <link linkend="io-priority">I/O priority</link> 
621  * of the request. 
622  * @cancellable: optional #GCancellable object, %NULL to ignore. 
623  * @callback: callback to call when the request is satisfied
624  * @user_data: the data to pass to callback function
625  *
626  * Request an asynchronous skip of @count bytes from the stream into the buffer
627  * starting at @buffer. When the operation is finished @callback will be called,
628  * giving the results.
629  *
630  * During an async request no other sync and async calls are allowed, and will
631  * result in %G_IO_ERROR_PENDING errors. 
632  *
633  * A value of @count larger than %G_MAXSSIZE will cause a %G_IO_ERROR_INVALID_ARGUMENT error.
634  *
635  * On success, the number of bytes skipped will be passed to the
636  * callback. It is not an error if this is not the same as the requested size, as it
637  * can happen e.g. near the end of a file, but generally we try to skip
638  * as many bytes as requested. Zero is returned on end of file
639  * (or if @count is zero), but never otherwise.
640  *
641  * Any outstanding i/o request with higher priority (lower numerical value) will
642  * be executed before an outstanding request with lower priority. Default
643  * priority is %G_PRIORITY_DEFAULT.
644  *
645  * The asyncronous methods have a default fallback that uses threads to implement
646  * asynchronicity, so they are optional for inheriting classes. However, if you
647  * override one you must override all.
648  **/
649 void
650 g_input_stream_skip_async (GInputStream        *stream,
651                            gsize                count,
652                            int                  io_priority,
653                            GCancellable        *cancellable,
654                            GAsyncReadyCallback  callback,
655                            gpointer             user_data)
656 {
657   GInputStreamClass *class;
658   GSimpleAsyncResult *simple;
659   GError *error = NULL;
660
661   g_return_if_fail (G_IS_INPUT_STREAM (stream));
662
663   if (count == 0)
664     {
665       simple = g_simple_async_result_new (G_OBJECT (stream),
666                                           callback,
667                                           user_data,
668                                           g_input_stream_skip_async);
669
670       g_simple_async_result_complete_in_idle (simple);
671       g_object_unref (simple);
672       return;
673     }
674   
675   if (((gssize) count) < 0)
676     {
677       g_simple_async_report_error_in_idle (G_OBJECT (stream),
678                                            callback,
679                                            user_data,
680                                            G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
681                                            _("Too large count value passed to g_input_stream_skip_async"));
682       return;
683     }
684
685   if (!g_input_stream_set_pending (stream, &error))
686     {
687       g_simple_async_report_gerror_in_idle (G_OBJECT (stream),
688                                             callback,
689                                             user_data,
690                                             error);
691       g_error_free (error);
692       return;
693     }
694
695   class = G_INPUT_STREAM_GET_CLASS (stream);
696   stream->priv->outstanding_callback = callback;
697   g_object_ref (stream);
698   class->skip_async (stream, count, io_priority, cancellable,
699                      async_ready_callback_wrapper, user_data);
700 }
701
702 /**
703  * g_input_stream_skip_finish:
704  * @stream: a #GInputStream.
705  * @result: a #GAsyncResult.
706  * @error: a #GError location to store the error occuring, or %NULL to 
707  * ignore.
708  * 
709  * Finishes a stream skip operation.
710  * 
711  * Returns: the size of the bytes skipped, or %-1 on error.
712  **/
713 gssize
714 g_input_stream_skip_finish (GInputStream  *stream,
715                             GAsyncResult  *result,
716                             GError       **error)
717 {
718   GSimpleAsyncResult *simple;
719   GInputStreamClass *class;
720
721   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), -1);
722   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), -1);
723
724   if (G_IS_SIMPLE_ASYNC_RESULT (result))
725     {
726       simple = G_SIMPLE_ASYNC_RESULT (result);
727       if (g_simple_async_result_propagate_error (simple, error))
728         return -1;
729
730       /* Special case skip of 0 bytes */
731       if (g_simple_async_result_get_source_tag (simple) == g_input_stream_skip_async)
732         return 0;
733     }
734
735   class = G_INPUT_STREAM_GET_CLASS (stream);
736   return class->skip_finish (stream, result, error);
737 }
738
739 /**
740  * g_input_stream_close_async:
741  * @stream: A #GInputStream.
742  * @io_priority: the <link linkend="io-priority">I/O priority</link> 
743  * of the request. 
744  * @cancellable: optional cancellable object
745  * @callback: callback to call when the request is satisfied
746  * @user_data: the data to pass to callback function
747  *
748  * Requests an asynchronous closes of the stream, releasing resources related to it.
749  * When the operation is finished @callback will be called, giving the results.
750  *
751  * For behaviour details see g_input_stream_close().
752  *
753  * The asyncronous methods have a default fallback that uses threads to implement
754  * asynchronicity, so they are optional for inheriting classes. However, if you
755  * override one you must override all.
756  **/
757 void
758 g_input_stream_close_async (GInputStream        *stream,
759                             int                  io_priority,
760                             GCancellable        *cancellable,
761                             GAsyncReadyCallback  callback,
762                             gpointer             user_data)
763 {
764   GInputStreamClass *class;
765   GSimpleAsyncResult *simple;
766   GError *error = NULL;
767
768   g_return_if_fail (G_IS_INPUT_STREAM (stream));
769
770   if (stream->priv->closed)
771     {
772       simple = g_simple_async_result_new (G_OBJECT (stream),
773                                           callback,
774                                           user_data,
775                                           g_input_stream_close_async);
776
777       g_simple_async_result_complete_in_idle (simple);
778       g_object_unref (simple);
779       return;
780     }
781
782   if (!g_input_stream_set_pending (stream, &error))
783     {
784       g_simple_async_report_gerror_in_idle (G_OBJECT (stream),
785                                             callback,
786                                             user_data,
787                                             error);
788       g_error_free (error);
789       return;
790     }
791   
792   class = G_INPUT_STREAM_GET_CLASS (stream);
793   stream->priv->outstanding_callback = callback;
794   g_object_ref (stream);
795   class->close_async (stream, io_priority, cancellable,
796                       async_ready_close_callback_wrapper, user_data);
797 }
798
799 /**
800  * g_input_stream_close_finish:
801  * @stream: a #GInputStream.
802  * @result: a #GAsyncResult.
803  * @error: a #GError location to store the error occuring, or %NULL to 
804  * ignore.
805  * 
806  * Finishes closing a stream asynchronously, started from g_input_stream_close_async().
807  * 
808  * Returns: %TRUE if the stream was closed successfully.
809  **/
810 gboolean
811 g_input_stream_close_finish (GInputStream  *stream,
812                              GAsyncResult  *result,
813                              GError       **error)
814 {
815   GSimpleAsyncResult *simple;
816   GInputStreamClass *class;
817
818   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), FALSE);
819   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
820
821   if (G_IS_SIMPLE_ASYNC_RESULT (result))
822     {
823       simple = G_SIMPLE_ASYNC_RESULT (result);
824       if (g_simple_async_result_propagate_error (simple, error))
825         return FALSE;
826
827       /* Special case already closed */
828       if (g_simple_async_result_get_source_tag (simple) == g_input_stream_close_async)
829         return TRUE;
830     }
831
832   class = G_INPUT_STREAM_GET_CLASS (stream);
833   return class->close_finish (stream, result, error);
834 }
835
836 /**
837  * g_input_stream_is_closed:
838  * @stream: input stream.
839  * 
840  * Checks if an input stream is closed.
841  * 
842  * Returns: %TRUE if the stream is closed.
843  **/
844 gboolean
845 g_input_stream_is_closed (GInputStream *stream)
846 {
847   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), TRUE);
848   
849   return stream->priv->closed;
850 }
851  
852 /**
853  * g_input_stream_has_pending:
854  * @stream: input stream.
855  * 
856  * Checks if an input stream has pending actions.
857  * 
858  * Returns: %TRUE if @stream has pending actions.
859  **/  
860 gboolean
861 g_input_stream_has_pending (GInputStream *stream)
862 {
863   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), TRUE);
864   
865   return stream->priv->pending;
866 }
867
868 /**
869  * g_input_stream_set_pending:
870  * @stream: input stream
871  * @error: a #GError location to store the error occuring, or %NULL to 
872  * ignore.
873  * 
874  * Sets @stream to have actions pending. If the pending flag is
875  * already set or @stream is closed, it will return %FALSE and set
876  * @error.
877  *
878  * Return value: %TRUE if pending was previously unset and is now set.
879  **/
880 gboolean
881 g_input_stream_set_pending (GInputStream *stream, GError **error)
882 {
883   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), FALSE);
884   
885   if (stream->priv->closed)
886     {
887       g_set_error (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
888                    _("Stream is already closed"));
889       return FALSE;
890     }
891   
892   if (stream->priv->pending)
893     {
894       g_set_error (error, G_IO_ERROR, G_IO_ERROR_PENDING,
895                    _("Stream has outstanding operation"));
896       return FALSE;
897     }
898   
899   stream->priv->pending = TRUE;
900   return TRUE;
901 }
902
903 /**
904  * g_input_stream_clear_pending:
905  * @stream: input stream
906  * 
907  * Clears the pending flag on @stream.
908  **/
909 void
910 g_input_stream_clear_pending (GInputStream *stream)
911 {
912   g_return_if_fail (G_IS_INPUT_STREAM (stream));
913   
914   stream->priv->pending = FALSE;
915 }
916
917 /********************************************
918  *   Default implementation of async ops    *
919  ********************************************/
920
921 typedef struct {
922   void              *buffer;
923   gsize              count_requested;
924   gssize             count_read;
925 } ReadData;
926
927 static void
928 read_async_thread (GSimpleAsyncResult *res,
929                    GObject            *object,
930                    GCancellable       *cancellable)
931 {
932   ReadData *op;
933   GInputStreamClass *class;
934   GError *error = NULL;
935  
936   op = g_simple_async_result_get_op_res_gpointer (res);
937
938   class = G_INPUT_STREAM_GET_CLASS (object);
939
940   op->count_read = class->read_fn (G_INPUT_STREAM (object),
941                                    op->buffer, op->count_requested,
942                                    cancellable, &error);
943   if (op->count_read == -1)
944     {
945       g_simple_async_result_set_from_error (res, error);
946       g_error_free (error);
947     }
948 }
949
950 static void
951 g_input_stream_real_read_async (GInputStream        *stream,
952                                 void                *buffer,
953                                 gsize                count,
954                                 int                  io_priority,
955                                 GCancellable        *cancellable,
956                                 GAsyncReadyCallback  callback,
957                                 gpointer             user_data)
958 {
959   GSimpleAsyncResult *res;
960   ReadData *op;
961   
962   op = g_new (ReadData, 1);
963   res = g_simple_async_result_new (G_OBJECT (stream), callback, user_data, g_input_stream_real_read_async);
964   g_simple_async_result_set_op_res_gpointer (res, op, g_free);
965   op->buffer = buffer;
966   op->count_requested = count;
967   
968   g_simple_async_result_run_in_thread (res, read_async_thread, io_priority, cancellable);
969   g_object_unref (res);
970 }
971
972 static gssize
973 g_input_stream_real_read_finish (GInputStream  *stream,
974                                  GAsyncResult  *result,
975                                  GError       **error)
976 {
977   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
978   ReadData *op;
979
980   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == 
981             g_input_stream_real_read_async);
982
983   op = g_simple_async_result_get_op_res_gpointer (simple);
984
985   return op->count_read;
986 }
987
988 typedef struct {
989   gsize count_requested;
990   gssize count_skipped;
991 } SkipData;
992
993
994 static void
995 skip_async_thread (GSimpleAsyncResult *res,
996                    GObject            *object,
997                    GCancellable       *cancellable)
998 {
999   SkipData *op;
1000   GInputStreamClass *class;
1001   GError *error = NULL;
1002   
1003   class = G_INPUT_STREAM_GET_CLASS (object);
1004   op = g_simple_async_result_get_op_res_gpointer (res);
1005   op->count_skipped = class->skip (G_INPUT_STREAM (object),
1006                                    op->count_requested,
1007                                    cancellable, &error);
1008   if (op->count_skipped == -1)
1009     {
1010       g_simple_async_result_set_from_error (res, error);
1011       g_error_free (error);
1012     }
1013 }
1014
1015 typedef struct {
1016   char buffer[8192];
1017   gsize count;
1018   gsize count_skipped;
1019   int io_prio;
1020   GCancellable *cancellable;
1021   gpointer user_data;
1022   GAsyncReadyCallback callback;
1023 } SkipFallbackAsyncData;
1024
1025 static void
1026 skip_callback_wrapper (GObject      *source_object,
1027                        GAsyncResult *res,
1028                        gpointer      user_data)
1029 {
1030   GInputStreamClass *class;
1031   SkipFallbackAsyncData *data = user_data;
1032   SkipData *op;
1033   GSimpleAsyncResult *simple;
1034   GError *error = NULL;
1035   gssize ret;
1036
1037   ret = g_input_stream_read_finish (G_INPUT_STREAM (source_object), res, &error);
1038
1039   if (ret > 0)
1040     {
1041       data->count -= ret;
1042       data->count_skipped += ret;
1043
1044       if (data->count > 0)
1045         {
1046           class = G_INPUT_STREAM_GET_CLASS (source_object);
1047           class->read_async (G_INPUT_STREAM (source_object), data->buffer, MIN (8192, data->count), data->io_prio, data->cancellable,
1048                              skip_callback_wrapper, data);
1049           return;
1050         }
1051     }
1052
1053   op = g_new0 (SkipData, 1);
1054   op->count_skipped = data->count_skipped;
1055   simple = g_simple_async_result_new (source_object,
1056                                       data->callback, data->user_data,
1057                                       g_input_stream_real_skip_async);
1058
1059   g_simple_async_result_set_op_res_gpointer (simple, op, g_free);
1060
1061   if (ret == -1)
1062     {
1063       if (data->count_skipped && 
1064           error->domain == G_IO_ERROR &&
1065           error->code == G_IO_ERROR_CANCELLED)
1066         { /* No error, return partial read */ }
1067       else
1068         g_simple_async_result_set_from_error (simple, error);
1069       g_error_free (error);
1070     }
1071
1072   /* Complete immediately, not in idle, since we're already in a mainloop callout */
1073   g_simple_async_result_complete (simple);
1074   g_object_unref (simple);
1075   
1076   g_free (data);
1077  }
1078
1079 static void
1080 g_input_stream_real_skip_async (GInputStream        *stream,
1081                                 gsize                count,
1082                                 int                  io_priority,
1083                                 GCancellable        *cancellable,
1084                                 GAsyncReadyCallback  callback,
1085                                 gpointer             user_data)
1086 {
1087   GInputStreamClass *class;
1088   SkipData *op;
1089   SkipFallbackAsyncData *data;
1090   GSimpleAsyncResult *res;
1091
1092   class = G_INPUT_STREAM_GET_CLASS (stream);
1093
1094   if (class->read_async == g_input_stream_real_read_async)
1095     {
1096       /* Read is thread-using async fallback.
1097        * Make skip use threads too, so that we can use a possible sync skip
1098        * implementation. */
1099       op = g_new0 (SkipData, 1);
1100       
1101       res = g_simple_async_result_new (G_OBJECT (stream), callback, user_data,
1102                                        g_input_stream_real_skip_async);
1103
1104       g_simple_async_result_set_op_res_gpointer (res, op, g_free);
1105
1106       op->count_requested = count;
1107
1108       g_simple_async_result_run_in_thread (res, skip_async_thread, io_priority, cancellable);
1109       g_object_unref (res);
1110     }
1111   else
1112     {
1113       /* TODO: Skip fallback uses too much memory, should do multiple read calls */
1114       
1115       /* There is a custom async read function, lets use that. */
1116       data = g_new (SkipFallbackAsyncData, 1);
1117       data->count = count;
1118       data->count_skipped = 0;
1119       data->io_prio = io_priority;
1120       data->cancellable = cancellable;
1121       data->callback = callback;
1122       data->user_data = user_data;
1123       class->read_async (stream, data->buffer, MIN (8192, count), io_priority, cancellable,
1124                          skip_callback_wrapper, data);
1125     }
1126
1127 }
1128
1129 static gssize
1130 g_input_stream_real_skip_finish (GInputStream  *stream,
1131                                  GAsyncResult  *result,
1132                                  GError       **error)
1133 {
1134   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
1135   SkipData *op;
1136
1137   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_input_stream_real_skip_async);
1138   op = g_simple_async_result_get_op_res_gpointer (simple);
1139   return op->count_skipped;
1140 }
1141
1142 static void
1143 close_async_thread (GSimpleAsyncResult *res,
1144                     GObject            *object,
1145                     GCancellable       *cancellable)
1146 {
1147   GInputStreamClass *class;
1148   GError *error = NULL;
1149   gboolean result;
1150
1151   /* Auto handling of cancelation disabled, and ignore
1152      cancellation, since we want to close things anyway, although
1153      possibly in a quick-n-dirty way. At least we never want to leak
1154      open handles */
1155   
1156   class = G_INPUT_STREAM_GET_CLASS (object);
1157   result = class->close_fn (G_INPUT_STREAM (object), cancellable, &error);
1158   if (!result)
1159     {
1160       g_simple_async_result_set_from_error (res, error);
1161       g_error_free (error);
1162     }
1163 }
1164
1165 static void
1166 g_input_stream_real_close_async (GInputStream        *stream,
1167                                  int                  io_priority,
1168                                  GCancellable        *cancellable,
1169                                  GAsyncReadyCallback  callback,
1170                                  gpointer             user_data)
1171 {
1172   GSimpleAsyncResult *res;
1173   
1174   res = g_simple_async_result_new (G_OBJECT (stream),
1175                                    callback,
1176                                    user_data,
1177                                    g_input_stream_real_close_async);
1178
1179   g_simple_async_result_set_handle_cancellation (res, FALSE);
1180   
1181   g_simple_async_result_run_in_thread (res,
1182                                        close_async_thread,
1183                                        io_priority,
1184                                        cancellable);
1185   g_object_unref (res);
1186 }
1187
1188 static gboolean
1189 g_input_stream_real_close_finish (GInputStream  *stream,
1190                                   GAsyncResult  *result,
1191                                   GError       **error)
1192 {
1193   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
1194   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_input_stream_real_close_async);
1195   return TRUE;
1196 }
1197
1198 #define __G_INPUT_STREAM_C__
1199 #include "gioaliasdef.c"