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