Initial commit
[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 #include "gioalias.h"
35
36 /**
37  * SECTION:ginputstream
38  * @short_description: Base class for implementing streaming input
39  * @include: gio/gio.h
40  *
41  * GInputStream has functions to read from a stream (g_input_stream_read()),
42  * to close a stream (g_input_stream_close()) and to skip some content
43  * (g_input_stream_skip()). 
44  *
45  * To copy the content of an input stream to an output stream without 
46  * manually handling the reads and writes, use g_output_stream_splice(). 
47  *
48  * All of these functions have async variants too.
49  **/
50
51 G_DEFINE_TYPE (GInputStream, g_input_stream, G_TYPE_OBJECT);
52
53 struct _GInputStreamPrivate {
54   guint closed : 1;
55   guint pending : 1;
56   GAsyncReadyCallback outstanding_callback;
57 };
58
59 static gssize   g_input_stream_real_skip         (GInputStream         *stream,
60                                                   gsize                 count,
61                                                   GCancellable         *cancellable,
62                                                   GError              **error);
63 static void     g_input_stream_real_read_async   (GInputStream         *stream,
64                                                   void                 *buffer,
65                                                   gsize                 count,
66                                                   int                   io_priority,
67                                                   GCancellable         *cancellable,
68                                                   GAsyncReadyCallback   callback,
69                                                   gpointer              user_data);
70 static gssize   g_input_stream_real_read_finish  (GInputStream         *stream,
71                                                   GAsyncResult         *result,
72                                                   GError              **error);
73 static void     g_input_stream_real_skip_async   (GInputStream         *stream,
74                                                   gsize                 count,
75                                                   int                   io_priority,
76                                                   GCancellable         *cancellable,
77                                                   GAsyncReadyCallback   callback,
78                                                   gpointer              data);
79 static gssize   g_input_stream_real_skip_finish  (GInputStream         *stream,
80                                                   GAsyncResult         *result,
81                                                   GError              **error);
82 static void     g_input_stream_real_close_async  (GInputStream         *stream,
83                                                   int                   io_priority,
84                                                   GCancellable         *cancellable,
85                                                   GAsyncReadyCallback   callback,
86                                                   gpointer              data);
87 static gboolean g_input_stream_real_close_finish (GInputStream         *stream,
88                                                   GAsyncResult         *result,
89                                                   GError              **error);
90
91 static void
92 g_input_stream_finalize (GObject *object)
93 {
94   G_OBJECT_CLASS (g_input_stream_parent_class)->finalize (object);
95 }
96
97 static void
98 g_input_stream_dispose (GObject *object)
99 {
100   GInputStream *stream;
101
102   stream = G_INPUT_STREAM (object);
103   
104   if (!stream->priv->closed)
105     g_input_stream_close (stream, NULL, NULL);
106
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 %s"), G_STRFUNC);
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_literal (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 %s"), G_STRFUNC);
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   if (G_IS_SEEKABLE (stream) && g_seekable_can_seek (G_SEEKABLE (stream)))
352     {
353       if (g_seekable_seek (G_SEEKABLE (stream),
354                            count,
355                            G_SEEK_CUR,
356                            cancellable,
357                            NULL))
358         return count;
359     }
360
361   /* If not seekable, or seek failed, fall back to reading data: */
362
363   class = G_INPUT_STREAM_GET_CLASS (stream);
364
365   read_bytes = 0;
366   while (1)
367     {
368       my_error = NULL;
369
370       ret = class->read_fn (stream, buffer, MIN (sizeof (buffer), count),
371                             cancellable, &my_error);
372       if (ret == -1)
373         {
374           if (read_bytes > 0 &&
375               my_error->domain == G_IO_ERROR &&
376               my_error->code == G_IO_ERROR_CANCELLED)
377             {
378               g_error_free (my_error);
379               return read_bytes;
380             }
381
382           g_propagate_error (error, my_error);
383           return -1;
384         }
385
386       count -= ret;
387       read_bytes += ret;
388
389       if (ret == 0 || count == 0)
390         return read_bytes;
391     }
392 }
393
394 /**
395  * g_input_stream_close:
396  * @stream: A #GInputStream.
397  * @cancellable: optional #GCancellable object, %NULL to ignore.
398  * @error: location to store the error occuring, or %NULL to ignore
399  *
400  * Closes the stream, releasing resources related to it.
401  *
402  * Once the stream is closed, all other operations will return %G_IO_ERROR_CLOSED.
403  * Closing a stream multiple times will not return an error.
404  *
405  * Streams will be automatically closed when the last reference
406  * is dropped, but you might want to call this function to make sure 
407  * resources are released as early as possible.
408  *
409  * Some streams might keep the backing store of the stream (e.g. a file descriptor)
410  * open after the stream is closed. See the documentation for the individual
411  * stream for details.
412  *
413  * On failure the first error that happened will be reported, but the close
414  * operation will finish as much as possible. A stream that failed to
415  * close will still return %G_IO_ERROR_CLOSED for all operations. Still, it
416  * is important to check and report the error to the user.
417  *
418  * If @cancellable is not NULL, then the operation can be cancelled by
419  * triggering the cancellable object from another thread. If the operation
420  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
421  * Cancelling a close will still leave the stream closed, but some streams
422  * can use a faster close that doesn't block to e.g. check errors. 
423  *
424  * Return value: %TRUE on success, %FALSE on failure
425  **/
426 gboolean
427 g_input_stream_close (GInputStream  *stream,
428                       GCancellable  *cancellable,
429                       GError       **error)
430 {
431   GInputStreamClass *class;
432   gboolean res;
433
434   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), FALSE);
435
436   class = G_INPUT_STREAM_GET_CLASS (stream);
437
438   if (stream->priv->closed)
439     return TRUE;
440
441   res = TRUE;
442
443   if (!g_input_stream_set_pending (stream, error))
444     return FALSE;
445
446   if (cancellable)
447     g_cancellable_push_current (cancellable);
448
449   if (class->close_fn)
450     res = class->close_fn (stream, cancellable, error);
451
452   if (cancellable)
453     g_cancellable_pop_current (cancellable);
454
455   g_input_stream_clear_pending (stream);
456   
457   stream->priv->closed = TRUE;
458   
459   return res;
460 }
461
462 static void
463 async_ready_callback_wrapper (GObject      *source_object,
464                               GAsyncResult *res,
465                               gpointer      user_data)
466 {
467   GInputStream *stream = G_INPUT_STREAM (source_object);
468
469   g_input_stream_clear_pending (stream);
470   if (stream->priv->outstanding_callback)
471     (*stream->priv->outstanding_callback) (source_object, res, user_data);
472   g_object_unref (stream);
473 }
474
475 static void
476 async_ready_close_callback_wrapper (GObject      *source_object,
477                                     GAsyncResult *res,
478                                     gpointer      user_data)
479 {
480   GInputStream *stream = G_INPUT_STREAM (source_object);
481
482   g_input_stream_clear_pending (stream);
483   stream->priv->closed = TRUE;
484   if (stream->priv->outstanding_callback)
485     (*stream->priv->outstanding_callback) (source_object, res, user_data);
486   g_object_unref (stream);
487 }
488
489 /**
490  * g_input_stream_read_async:
491  * @stream: A #GInputStream.
492  * @buffer: a buffer to read data into (which should be at least count bytes long).
493  * @count: the number of bytes that will be read from the stream
494  * @io_priority: the <link linkend="io-priority">I/O priority</link> 
495  * of the request. 
496  * @cancellable: optional #GCancellable object, %NULL to ignore.
497  * @callback: callback to call when the request is satisfied
498  * @user_data: the data to pass to callback function
499  *
500  * Request an asynchronous read of @count bytes from the stream into the buffer
501  * starting at @buffer. When the operation is finished @callback will be called. 
502  * You can then call g_input_stream_read_finish() to get the result of the 
503  * operation.
504  *
505  * During an async request no other sync and async calls are allowed on @stream, and will
506  * result in %G_IO_ERROR_PENDING errors. 
507  *
508  * A value of @count larger than %G_MAXSSIZE will cause a %G_IO_ERROR_INVALID_ARGUMENT error.
509  *
510  * On success, the number of bytes read into the buffer will be passed to the
511  * callback. It is not an error if this is not the same as the requested size, as it
512  * can happen e.g. near the end of a file, but generally we try to read
513  * as many bytes as requested. Zero is returned on end of file
514  * (or if @count is zero),  but never otherwise.
515  *
516  * Any outstanding i/o request with higher priority (lower numerical value) will
517  * be executed before an outstanding request with lower priority. Default
518  * priority is %G_PRIORITY_DEFAULT.
519  *
520  * The asyncronous methods have a default fallback that uses threads to implement
521  * asynchronicity, so they are optional for inheriting classes. However, if you
522  * override one you must override all.
523  **/
524 void
525 g_input_stream_read_async (GInputStream        *stream,
526                            void                *buffer,
527                            gsize                count,
528                            int                  io_priority,
529                            GCancellable        *cancellable,
530                            GAsyncReadyCallback  callback,
531                            gpointer             user_data)
532 {
533   GInputStreamClass *class;
534   GSimpleAsyncResult *simple;
535   GError *error = NULL;
536
537   g_return_if_fail (G_IS_INPUT_STREAM (stream));
538   g_return_if_fail (buffer != NULL);
539
540   if (count == 0)
541     {
542       simple = g_simple_async_result_new (G_OBJECT (stream),
543                                           callback,
544                                           user_data,
545                                           g_input_stream_read_async);
546       g_simple_async_result_complete_in_idle (simple);
547       g_object_unref (simple);
548       return;
549     }
550   
551   if (((gssize) count) < 0)
552     {
553       g_simple_async_report_error_in_idle (G_OBJECT (stream),
554                                            callback,
555                                            user_data,
556                                            G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
557                                            _("Too large count value passed to %s"),
558                                            G_STRFUNC);
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.
627  * When the operation is finished @callback will be called. 
628  * You can then call g_input_stream_skip_finish() to get the result of the 
629  * operation.
630  *
631  * During an async request no other sync and async calls are allowed, and will
632  * result in %G_IO_ERROR_PENDING errors. 
633  *
634  * A value of @count larger than %G_MAXSSIZE will cause a %G_IO_ERROR_INVALID_ARGUMENT error.
635  *
636  * On success, the number of bytes skipped will be passed to the
637  * callback. It is not an error if this is not the same as the requested size, as it
638  * can happen e.g. near the end of a file, but generally we try to skip
639  * as many bytes as requested. Zero is returned on end of file
640  * (or if @count is zero), but never otherwise.
641  *
642  * Any outstanding i/o request with higher priority (lower numerical value) will
643  * be executed before an outstanding request with lower priority. Default
644  * priority is %G_PRIORITY_DEFAULT.
645  *
646  * The asyncronous methods have a default fallback that uses threads to implement
647  * asynchronicity, so they are optional for inheriting classes. However, if you
648  * override one you must override all.
649  **/
650 void
651 g_input_stream_skip_async (GInputStream        *stream,
652                            gsize                count,
653                            int                  io_priority,
654                            GCancellable        *cancellable,
655                            GAsyncReadyCallback  callback,
656                            gpointer             user_data)
657 {
658   GInputStreamClass *class;
659   GSimpleAsyncResult *simple;
660   GError *error = NULL;
661
662   g_return_if_fail (G_IS_INPUT_STREAM (stream));
663
664   if (count == 0)
665     {
666       simple = g_simple_async_result_new (G_OBJECT (stream),
667                                           callback,
668                                           user_data,
669                                           g_input_stream_skip_async);
670
671       g_simple_async_result_complete_in_idle (simple);
672       g_object_unref (simple);
673       return;
674     }
675   
676   if (((gssize) count) < 0)
677     {
678       g_simple_async_report_error_in_idle (G_OBJECT (stream),
679                                            callback,
680                                            user_data,
681                                            G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
682                                            _("Too large count value passed to %s"),
683                                            G_STRFUNC);
684       return;
685     }
686
687   if (!g_input_stream_set_pending (stream, &error))
688     {
689       g_simple_async_report_gerror_in_idle (G_OBJECT (stream),
690                                             callback,
691                                             user_data,
692                                             error);
693       g_error_free (error);
694       return;
695     }
696
697   class = G_INPUT_STREAM_GET_CLASS (stream);
698   stream->priv->outstanding_callback = callback;
699   g_object_ref (stream);
700   class->skip_async (stream, count, io_priority, cancellable,
701                      async_ready_callback_wrapper, user_data);
702 }
703
704 /**
705  * g_input_stream_skip_finish:
706  * @stream: a #GInputStream.
707  * @result: a #GAsyncResult.
708  * @error: a #GError location to store the error occuring, or %NULL to 
709  * ignore.
710  * 
711  * Finishes a stream skip operation.
712  * 
713  * Returns: the size of the bytes skipped, or %-1 on error.
714  **/
715 gssize
716 g_input_stream_skip_finish (GInputStream  *stream,
717                             GAsyncResult  *result,
718                             GError       **error)
719 {
720   GSimpleAsyncResult *simple;
721   GInputStreamClass *class;
722
723   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), -1);
724   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), -1);
725
726   if (G_IS_SIMPLE_ASYNC_RESULT (result))
727     {
728       simple = G_SIMPLE_ASYNC_RESULT (result);
729       if (g_simple_async_result_propagate_error (simple, error))
730         return -1;
731
732       /* Special case skip of 0 bytes */
733       if (g_simple_async_result_get_source_tag (simple) == g_input_stream_skip_async)
734         return 0;
735     }
736
737   class = G_INPUT_STREAM_GET_CLASS (stream);
738   return class->skip_finish (stream, result, error);
739 }
740
741 /**
742  * g_input_stream_close_async:
743  * @stream: A #GInputStream.
744  * @io_priority: the <link linkend="io-priority">I/O priority</link> 
745  * of the request. 
746  * @cancellable: optional cancellable object
747  * @callback: callback to call when the request is satisfied
748  * @user_data: the data to pass to callback function
749  *
750  * Requests an asynchronous closes of the stream, releasing resources related to it.
751  * When the operation is finished @callback will be called. 
752  * You can then call g_input_stream_close_finish() to get the result of the 
753  * operation.
754  *
755  * For behaviour details see g_input_stream_close().
756  *
757  * The asyncronous methods have a default fallback that uses threads to implement
758  * asynchronicity, so they are optional for inheriting classes. However, if you
759  * override one you must override all.
760  **/
761 void
762 g_input_stream_close_async (GInputStream        *stream,
763                             int                  io_priority,
764                             GCancellable        *cancellable,
765                             GAsyncReadyCallback  callback,
766                             gpointer             user_data)
767 {
768   GInputStreamClass *class;
769   GSimpleAsyncResult *simple;
770   GError *error = NULL;
771
772   g_return_if_fail (G_IS_INPUT_STREAM (stream));
773
774   if (stream->priv->closed)
775     {
776       simple = g_simple_async_result_new (G_OBJECT (stream),
777                                           callback,
778                                           user_data,
779                                           g_input_stream_close_async);
780
781       g_simple_async_result_complete_in_idle (simple);
782       g_object_unref (simple);
783       return;
784     }
785
786   if (!g_input_stream_set_pending (stream, &error))
787     {
788       g_simple_async_report_gerror_in_idle (G_OBJECT (stream),
789                                             callback,
790                                             user_data,
791                                             error);
792       g_error_free (error);
793       return;
794     }
795   
796   class = G_INPUT_STREAM_GET_CLASS (stream);
797   stream->priv->outstanding_callback = callback;
798   g_object_ref (stream);
799   class->close_async (stream, io_priority, cancellable,
800                       async_ready_close_callback_wrapper, user_data);
801 }
802
803 /**
804  * g_input_stream_close_finish:
805  * @stream: a #GInputStream.
806  * @result: a #GAsyncResult.
807  * @error: a #GError location to store the error occuring, or %NULL to 
808  * ignore.
809  * 
810  * Finishes closing a stream asynchronously, started from g_input_stream_close_async().
811  * 
812  * Returns: %TRUE if the stream was closed successfully.
813  **/
814 gboolean
815 g_input_stream_close_finish (GInputStream  *stream,
816                              GAsyncResult  *result,
817                              GError       **error)
818 {
819   GSimpleAsyncResult *simple;
820   GInputStreamClass *class;
821
822   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), FALSE);
823   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
824
825   if (G_IS_SIMPLE_ASYNC_RESULT (result))
826     {
827       simple = G_SIMPLE_ASYNC_RESULT (result);
828       if (g_simple_async_result_propagate_error (simple, error))
829         return FALSE;
830
831       /* Special case already closed */
832       if (g_simple_async_result_get_source_tag (simple) == g_input_stream_close_async)
833         return TRUE;
834     }
835
836   class = G_INPUT_STREAM_GET_CLASS (stream);
837   return class->close_finish (stream, result, error);
838 }
839
840 /**
841  * g_input_stream_is_closed:
842  * @stream: input stream.
843  * 
844  * Checks if an input stream is closed.
845  * 
846  * Returns: %TRUE if the stream is closed.
847  **/
848 gboolean
849 g_input_stream_is_closed (GInputStream *stream)
850 {
851   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), TRUE);
852   
853   return stream->priv->closed;
854 }
855  
856 /**
857  * g_input_stream_has_pending:
858  * @stream: input stream.
859  * 
860  * Checks if an input stream has pending actions.
861  * 
862  * Returns: %TRUE if @stream has pending actions.
863  **/  
864 gboolean
865 g_input_stream_has_pending (GInputStream *stream)
866 {
867   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), TRUE);
868   
869   return stream->priv->pending;
870 }
871
872 /**
873  * g_input_stream_set_pending:
874  * @stream: input stream
875  * @error: a #GError location to store the error occuring, or %NULL to 
876  * ignore.
877  * 
878  * Sets @stream to have actions pending. If the pending flag is
879  * already set or @stream is closed, it will return %FALSE and set
880  * @error.
881  *
882  * Return value: %TRUE if pending was previously unset and is now set.
883  **/
884 gboolean
885 g_input_stream_set_pending (GInputStream *stream, GError **error)
886 {
887   g_return_val_if_fail (G_IS_INPUT_STREAM (stream), FALSE);
888   
889   if (stream->priv->closed)
890     {
891       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
892                            _("Stream is already closed"));
893       return FALSE;
894     }
895   
896   if (stream->priv->pending)
897     {
898       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
899                 /* Translators: This is an error you get if there is already an
900                  * operation running against this stream when you try to start
901                  * one */
902                  _("Stream has outstanding operation"));
903       return FALSE;
904     }
905   
906   stream->priv->pending = TRUE;
907   return TRUE;
908 }
909
910 /**
911  * g_input_stream_clear_pending:
912  * @stream: input stream
913  * 
914  * Clears the pending flag on @stream.
915  **/
916 void
917 g_input_stream_clear_pending (GInputStream *stream)
918 {
919   g_return_if_fail (G_IS_INPUT_STREAM (stream));
920   
921   stream->priv->pending = FALSE;
922 }
923
924 /********************************************
925  *   Default implementation of async ops    *
926  ********************************************/
927
928 typedef struct {
929   void              *buffer;
930   gsize              count_requested;
931   gssize             count_read;
932 } ReadData;
933
934 static void
935 read_async_thread (GSimpleAsyncResult *res,
936                    GObject            *object,
937                    GCancellable       *cancellable)
938 {
939   ReadData *op;
940   GInputStreamClass *class;
941   GError *error = NULL;
942  
943   op = g_simple_async_result_get_op_res_gpointer (res);
944
945   class = G_INPUT_STREAM_GET_CLASS (object);
946
947   op->count_read = class->read_fn (G_INPUT_STREAM (object),
948                                    op->buffer, op->count_requested,
949                                    cancellable, &error);
950   if (op->count_read == -1)
951     {
952       g_simple_async_result_set_from_error (res, error);
953       g_error_free (error);
954     }
955 }
956
957 static void
958 g_input_stream_real_read_async (GInputStream        *stream,
959                                 void                *buffer,
960                                 gsize                count,
961                                 int                  io_priority,
962                                 GCancellable        *cancellable,
963                                 GAsyncReadyCallback  callback,
964                                 gpointer             user_data)
965 {
966   GSimpleAsyncResult *res;
967   ReadData *op;
968   
969   op = g_new (ReadData, 1);
970   res = g_simple_async_result_new (G_OBJECT (stream), callback, user_data, g_input_stream_real_read_async);
971   g_simple_async_result_set_op_res_gpointer (res, op, g_free);
972   op->buffer = buffer;
973   op->count_requested = count;
974   
975   g_simple_async_result_run_in_thread (res, read_async_thread, io_priority, cancellable);
976   g_object_unref (res);
977 }
978
979 static gssize
980 g_input_stream_real_read_finish (GInputStream  *stream,
981                                  GAsyncResult  *result,
982                                  GError       **error)
983 {
984   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
985   ReadData *op;
986
987   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == 
988             g_input_stream_real_read_async);
989
990   op = g_simple_async_result_get_op_res_gpointer (simple);
991
992   return op->count_read;
993 }
994
995 typedef struct {
996   gsize count_requested;
997   gssize count_skipped;
998 } SkipData;
999
1000
1001 static void
1002 skip_async_thread (GSimpleAsyncResult *res,
1003                    GObject            *object,
1004                    GCancellable       *cancellable)
1005 {
1006   SkipData *op;
1007   GInputStreamClass *class;
1008   GError *error = NULL;
1009   
1010   class = G_INPUT_STREAM_GET_CLASS (object);
1011   op = g_simple_async_result_get_op_res_gpointer (res);
1012   op->count_skipped = class->skip (G_INPUT_STREAM (object),
1013                                    op->count_requested,
1014                                    cancellable, &error);
1015   if (op->count_skipped == -1)
1016     {
1017       g_simple_async_result_set_from_error (res, error);
1018       g_error_free (error);
1019     }
1020 }
1021
1022 typedef struct {
1023   char buffer[8192];
1024   gsize count;
1025   gsize count_skipped;
1026   int io_prio;
1027   GCancellable *cancellable;
1028   gpointer user_data;
1029   GAsyncReadyCallback callback;
1030 } SkipFallbackAsyncData;
1031
1032 static void
1033 skip_callback_wrapper (GObject      *source_object,
1034                        GAsyncResult *res,
1035                        gpointer      user_data)
1036 {
1037   GInputStreamClass *class;
1038   SkipFallbackAsyncData *data = user_data;
1039   SkipData *op;
1040   GSimpleAsyncResult *simple;
1041   GError *error = NULL;
1042   gssize ret;
1043
1044   ret = g_input_stream_read_finish (G_INPUT_STREAM (source_object), res, &error);
1045
1046   if (ret > 0)
1047     {
1048       data->count -= ret;
1049       data->count_skipped += ret;
1050
1051       if (data->count > 0)
1052         {
1053           class = G_INPUT_STREAM_GET_CLASS (source_object);
1054           class->read_async (G_INPUT_STREAM (source_object), data->buffer, MIN (8192, data->count), data->io_prio, data->cancellable,
1055                              skip_callback_wrapper, data);
1056           return;
1057         }
1058     }
1059
1060   op = g_new0 (SkipData, 1);
1061   op->count_skipped = data->count_skipped;
1062   simple = g_simple_async_result_new (source_object,
1063                                       data->callback, data->user_data,
1064                                       g_input_stream_real_skip_async);
1065
1066   g_simple_async_result_set_op_res_gpointer (simple, op, g_free);
1067
1068   if (ret == -1)
1069     {
1070       if (data->count_skipped && 
1071           error->domain == G_IO_ERROR &&
1072           error->code == G_IO_ERROR_CANCELLED)
1073         { /* No error, return partial read */ }
1074       else
1075         g_simple_async_result_set_from_error (simple, error);
1076       g_error_free (error);
1077     }
1078
1079   /* Complete immediately, not in idle, since we're already in a mainloop callout */
1080   g_simple_async_result_complete (simple);
1081   g_object_unref (simple);
1082   
1083   g_free (data);
1084  }
1085
1086 static void
1087 g_input_stream_real_skip_async (GInputStream        *stream,
1088                                 gsize                count,
1089                                 int                  io_priority,
1090                                 GCancellable        *cancellable,
1091                                 GAsyncReadyCallback  callback,
1092                                 gpointer             user_data)
1093 {
1094   GInputStreamClass *class;
1095   SkipData *op;
1096   SkipFallbackAsyncData *data;
1097   GSimpleAsyncResult *res;
1098
1099   class = G_INPUT_STREAM_GET_CLASS (stream);
1100
1101   if (class->read_async == g_input_stream_real_read_async)
1102     {
1103       /* Read is thread-using async fallback.
1104        * Make skip use threads too, so that we can use a possible sync skip
1105        * implementation. */
1106       op = g_new0 (SkipData, 1);
1107       
1108       res = g_simple_async_result_new (G_OBJECT (stream), callback, user_data,
1109                                        g_input_stream_real_skip_async);
1110
1111       g_simple_async_result_set_op_res_gpointer (res, op, g_free);
1112
1113       op->count_requested = count;
1114
1115       g_simple_async_result_run_in_thread (res, skip_async_thread, io_priority, cancellable);
1116       g_object_unref (res);
1117     }
1118   else
1119     {
1120       /* TODO: Skip fallback uses too much memory, should do multiple read calls */
1121       
1122       /* There is a custom async read function, lets use that. */
1123       data = g_new (SkipFallbackAsyncData, 1);
1124       data->count = count;
1125       data->count_skipped = 0;
1126       data->io_prio = io_priority;
1127       data->cancellable = cancellable;
1128       data->callback = callback;
1129       data->user_data = user_data;
1130       class->read_async (stream, data->buffer, MIN (8192, count), io_priority, cancellable,
1131                          skip_callback_wrapper, data);
1132     }
1133
1134 }
1135
1136 static gssize
1137 g_input_stream_real_skip_finish (GInputStream  *stream,
1138                                  GAsyncResult  *result,
1139                                  GError       **error)
1140 {
1141   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
1142   SkipData *op;
1143
1144   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_input_stream_real_skip_async);
1145   op = g_simple_async_result_get_op_res_gpointer (simple);
1146   return op->count_skipped;
1147 }
1148
1149 static void
1150 close_async_thread (GSimpleAsyncResult *res,
1151                     GObject            *object,
1152                     GCancellable       *cancellable)
1153 {
1154   GInputStreamClass *class;
1155   GError *error = NULL;
1156   gboolean result;
1157
1158   /* Auto handling of cancelation disabled, and ignore
1159      cancellation, since we want to close things anyway, although
1160      possibly in a quick-n-dirty way. At least we never want to leak
1161      open handles */
1162
1163   class = G_INPUT_STREAM_GET_CLASS (object);
1164   if (class->close_fn)
1165     {
1166       result = class->close_fn (G_INPUT_STREAM (object), cancellable, &error);
1167       if (!result)
1168         {
1169           g_simple_async_result_set_from_error (res, error);
1170           g_error_free (error);
1171         }
1172     }
1173 }
1174
1175 static void
1176 g_input_stream_real_close_async (GInputStream        *stream,
1177                                  int                  io_priority,
1178                                  GCancellable        *cancellable,
1179                                  GAsyncReadyCallback  callback,
1180                                  gpointer             user_data)
1181 {
1182   GSimpleAsyncResult *res;
1183   
1184   res = g_simple_async_result_new (G_OBJECT (stream),
1185                                    callback,
1186                                    user_data,
1187                                    g_input_stream_real_close_async);
1188
1189   g_simple_async_result_set_handle_cancellation (res, FALSE);
1190   
1191   g_simple_async_result_run_in_thread (res,
1192                                        close_async_thread,
1193                                        io_priority,
1194                                        cancellable);
1195   g_object_unref (res);
1196 }
1197
1198 static gboolean
1199 g_input_stream_real_close_finish (GInputStream  *stream,
1200                                   GAsyncResult  *result,
1201                                   GError       **error)
1202 {
1203   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
1204   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_input_stream_real_close_async);
1205   return TRUE;
1206 }
1207
1208 #define __G_INPUT_STREAM_C__
1209 #include "gioaliasdef.c"