gio: add g_async_result_is_tagged()
[platform/upstream/glib.git] / gio / gbufferedinputstream.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  * Copyright (C) 2007 Jürg Billeter
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General
17  * Public License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
19  * Boston, MA 02111-1307, USA.
20  *
21  * Author: Christian Kellner <gicmo@gnome.org>
22  */
23
24 #include "config.h"
25 #include "gbufferedinputstream.h"
26 #include "ginputstream.h"
27 #include "gcancellable.h"
28 #include "gasyncresult.h"
29 #include "gsimpleasyncresult.h"
30 #include "gseekable.h"
31 #include "gioerror.h"
32 #include <string.h>
33 #include "glibintl.h"
34
35
36 /**
37  * SECTION:gbufferedinputstream
38  * @short_description: Buffered Input Stream
39  * @include: gio/gio.h
40  * @see_also: #GFilterInputStream, #GInputStream
41  *
42  * Buffered input stream implements #GFilterInputStream and provides
43  * for buffered reads.
44  *
45  * By default, #GBufferedInputStream's buffer size is set at 4 kilobytes.
46  *
47  * To create a buffered input stream, use g_buffered_input_stream_new(),
48  * or g_buffered_input_stream_new_sized() to specify the buffer's size at
49  * construction.
50  *
51  * To get the size of a buffer within a buffered input stream, use
52  * g_buffered_input_stream_get_buffer_size(). To change the size of a
53  * buffered input stream's buffer, use
54  * g_buffered_input_stream_set_buffer_size(). Note that the buffer's size
55  * cannot be reduced below the size of the data within the buffer.
56  */
57
58
59 #define DEFAULT_BUFFER_SIZE 4096
60
61 struct _GBufferedInputStreamPrivate {
62   guint8 *buffer;
63   gsize   len;
64   gsize   pos;
65   gsize   end;
66   GAsyncReadyCallback outstanding_callback;
67 };
68
69 enum {
70   PROP_0,
71   PROP_BUFSIZE
72 };
73
74 static void g_buffered_input_stream_set_property  (GObject      *object,
75                                                    guint         prop_id,
76                                                    const GValue *value,
77                                                    GParamSpec   *pspec);
78
79 static void g_buffered_input_stream_get_property  (GObject      *object,
80                                                    guint         prop_id,
81                                                    GValue       *value,
82                                                    GParamSpec   *pspec);
83 static void g_buffered_input_stream_finalize      (GObject *object);
84
85
86 static gssize g_buffered_input_stream_skip             (GInputStream          *stream,
87                                                         gsize                  count,
88                                                         GCancellable          *cancellable,
89                                                         GError               **error);
90 static void   g_buffered_input_stream_skip_async       (GInputStream          *stream,
91                                                         gsize                  count,
92                                                         int                    io_priority,
93                                                         GCancellable          *cancellable,
94                                                         GAsyncReadyCallback    callback,
95                                                         gpointer               user_data);
96 static gssize g_buffered_input_stream_skip_finish      (GInputStream          *stream,
97                                                         GAsyncResult          *result,
98                                                         GError               **error);
99 static gssize g_buffered_input_stream_read             (GInputStream          *stream,
100                                                         void                  *buffer,
101                                                         gsize                  count,
102                                                         GCancellable          *cancellable,
103                                                         GError               **error);
104 static gssize g_buffered_input_stream_real_fill        (GBufferedInputStream  *stream,
105                                                         gssize                 count,
106                                                         GCancellable          *cancellable,
107                                                         GError               **error);
108 static void   g_buffered_input_stream_real_fill_async  (GBufferedInputStream  *stream,
109                                                         gssize                 count,
110                                                         int                    io_priority,
111                                                         GCancellable          *cancellable,
112                                                         GAsyncReadyCallback    callback,
113                                                         gpointer               user_data);
114 static gssize g_buffered_input_stream_real_fill_finish (GBufferedInputStream  *stream,
115                                                         GAsyncResult          *result,
116                                                         GError               **error);
117
118 static void     g_buffered_input_stream_seekable_iface_init (GSeekableIface  *iface);
119 static goffset  g_buffered_input_stream_tell                (GSeekable       *seekable);
120 static gboolean g_buffered_input_stream_can_seek            (GSeekable       *seekable);
121 static gboolean g_buffered_input_stream_seek                (GSeekable       *seekable,
122                                                              goffset          offset,
123                                                              GSeekType        type,
124                                                              GCancellable    *cancellable,
125                                                              GError         **error);
126 static gboolean g_buffered_input_stream_can_truncate        (GSeekable       *seekable);
127 static gboolean g_buffered_input_stream_truncate            (GSeekable       *seekable,
128                                                              goffset          offset,
129                                                              GCancellable    *cancellable,
130                                                              GError         **error);
131
132 static void     g_buffered_input_stream_finalize            (GObject         *object);
133
134 static void compact_buffer (GBufferedInputStream *stream);
135
136 G_DEFINE_TYPE_WITH_CODE (GBufferedInputStream,
137                          g_buffered_input_stream,
138                          G_TYPE_FILTER_INPUT_STREAM,
139                          G_IMPLEMENT_INTERFACE (G_TYPE_SEEKABLE,
140                                                 g_buffered_input_stream_seekable_iface_init))
141
142 static void
143 g_buffered_input_stream_class_init (GBufferedInputStreamClass *klass)
144 {
145   GObjectClass *object_class;
146   GInputStreamClass *istream_class;
147   GBufferedInputStreamClass *bstream_class;
148
149   g_type_class_add_private (klass, sizeof (GBufferedInputStreamPrivate));
150
151   object_class = G_OBJECT_CLASS (klass);
152   object_class->get_property = g_buffered_input_stream_get_property;
153   object_class->set_property = g_buffered_input_stream_set_property;
154   object_class->finalize     = g_buffered_input_stream_finalize;
155
156   istream_class = G_INPUT_STREAM_CLASS (klass);
157   istream_class->skip = g_buffered_input_stream_skip;
158   istream_class->skip_async  = g_buffered_input_stream_skip_async;
159   istream_class->skip_finish = g_buffered_input_stream_skip_finish;
160   istream_class->read_fn = g_buffered_input_stream_read;
161
162   bstream_class = G_BUFFERED_INPUT_STREAM_CLASS (klass);
163   bstream_class->fill = g_buffered_input_stream_real_fill;
164   bstream_class->fill_async = g_buffered_input_stream_real_fill_async;
165   bstream_class->fill_finish = g_buffered_input_stream_real_fill_finish;
166
167   g_object_class_install_property (object_class,
168                                    PROP_BUFSIZE,
169                                    g_param_spec_uint ("buffer-size",
170                                                       P_("Buffer Size"),
171                                                       P_("The size of the backend buffer"),
172                                                       1,
173                                                       G_MAXUINT,
174                                                       DEFAULT_BUFFER_SIZE,
175                                                       G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
176                                                       G_PARAM_STATIC_NAME|G_PARAM_STATIC_NICK|G_PARAM_STATIC_BLURB));
177
178
179 }
180
181 /**
182  * g_buffered_input_stream_get_buffer_size:
183  * @stream: a #GBufferedInputStream
184  *
185  * Gets the size of the input buffer.
186  *
187  * Returns: the current buffer size.
188  */
189 gsize
190 g_buffered_input_stream_get_buffer_size (GBufferedInputStream  *stream)
191 {
192   g_return_val_if_fail (G_IS_BUFFERED_INPUT_STREAM (stream), 0);
193
194   return stream->priv->len;
195 }
196
197 /**
198  * g_buffered_input_stream_set_buffer_size:
199  * @stream: a #GBufferedInputStream
200  * @size: a #gsize
201  *
202  * Sets the size of the internal buffer of @stream to @size, or to the
203  * size of the contents of the buffer. The buffer can never be resized
204  * smaller than its current contents.
205  */
206 void
207 g_buffered_input_stream_set_buffer_size (GBufferedInputStream *stream,
208                                          gsize                 size)
209 {
210   GBufferedInputStreamPrivate *priv;
211   gsize in_buffer;
212   guint8 *buffer;
213
214   g_return_if_fail (G_IS_BUFFERED_INPUT_STREAM (stream));
215
216   priv = stream->priv;
217
218   if (priv->len == size)
219     return;
220
221   if (priv->buffer)
222     {
223       in_buffer = priv->end - priv->pos;
224
225       /* Never resize smaller than current buffer contents */
226       size = MAX (size, in_buffer);
227
228       buffer = g_malloc (size);
229       memcpy (buffer, priv->buffer + priv->pos, in_buffer);
230       priv->len = size;
231       priv->pos = 0;
232       priv->end = in_buffer;
233       g_free (priv->buffer);
234       priv->buffer = buffer;
235     }
236   else
237     {
238       priv->len = size;
239       priv->pos = 0;
240       priv->end = 0;
241       priv->buffer = g_malloc (size);
242     }
243
244   g_object_notify (G_OBJECT (stream), "buffer-size");
245 }
246
247 static void
248 g_buffered_input_stream_set_property (GObject      *object,
249                                       guint         prop_id,
250                                       const GValue *value,
251                                       GParamSpec   *pspec)
252 {
253   GBufferedInputStream        *bstream;
254
255   bstream = G_BUFFERED_INPUT_STREAM (object);
256
257   switch (prop_id)
258     {
259     case PROP_BUFSIZE:
260       g_buffered_input_stream_set_buffer_size (bstream, g_value_get_uint (value));
261       break;
262
263     default:
264       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
265       break;
266     }
267 }
268
269 static void
270 g_buffered_input_stream_get_property (GObject    *object,
271                                       guint       prop_id,
272                                       GValue     *value,
273                                       GParamSpec *pspec)
274 {
275   GBufferedInputStreamPrivate *priv;
276   GBufferedInputStream        *bstream;
277
278   bstream = G_BUFFERED_INPUT_STREAM (object);
279   priv = bstream->priv;
280
281   switch (prop_id)
282     {
283     case PROP_BUFSIZE:
284       g_value_set_uint (value, priv->len);
285       break;
286
287     default:
288       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
289       break;
290     }
291 }
292
293 static void
294 g_buffered_input_stream_finalize (GObject *object)
295 {
296   GBufferedInputStreamPrivate *priv;
297   GBufferedInputStream        *stream;
298
299   stream = G_BUFFERED_INPUT_STREAM (object);
300   priv = stream->priv;
301
302   g_free (priv->buffer);
303
304   G_OBJECT_CLASS (g_buffered_input_stream_parent_class)->finalize (object);
305 }
306
307 static void
308 g_buffered_input_stream_seekable_iface_init (GSeekableIface *iface)
309 {
310   iface->tell         = g_buffered_input_stream_tell;
311   iface->can_seek     = g_buffered_input_stream_can_seek;
312   iface->seek         = g_buffered_input_stream_seek;
313   iface->can_truncate = g_buffered_input_stream_can_truncate;
314   iface->truncate_fn  = g_buffered_input_stream_truncate;
315 }
316
317 static void
318 g_buffered_input_stream_init (GBufferedInputStream *stream)
319 {
320   stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (stream,
321                                               G_TYPE_BUFFERED_INPUT_STREAM,
322                                               GBufferedInputStreamPrivate);
323 }
324
325
326 /**
327  * g_buffered_input_stream_new:
328  * @base_stream: a #GInputStream
329  *
330  * Creates a new #GInputStream from the given @base_stream, with
331  * a buffer set to the default size (4 kilobytes).
332  *
333  * Returns: a #GInputStream for the given @base_stream.
334  */
335 GInputStream *
336 g_buffered_input_stream_new (GInputStream *base_stream)
337 {
338   GInputStream *stream;
339
340   g_return_val_if_fail (G_IS_INPUT_STREAM (base_stream), NULL);
341
342   stream = g_object_new (G_TYPE_BUFFERED_INPUT_STREAM,
343                          "base-stream", base_stream,
344                          NULL);
345
346   return stream;
347 }
348
349 /**
350  * g_buffered_input_stream_new_sized:
351  * @base_stream: a #GInputStream
352  * @size: a #gsize
353  *
354  * Creates a new #GBufferedInputStream from the given @base_stream,
355  * with a buffer set to @size.
356  *
357  * Returns: a #GInputStream.
358  */
359 GInputStream *
360 g_buffered_input_stream_new_sized (GInputStream *base_stream,
361                                    gsize         size)
362 {
363   GInputStream *stream;
364
365   g_return_val_if_fail (G_IS_INPUT_STREAM (base_stream), NULL);
366
367   stream = g_object_new (G_TYPE_BUFFERED_INPUT_STREAM,
368                          "base-stream", base_stream,
369                          "buffer-size", (guint)size,
370                          NULL);
371
372   return stream;
373 }
374
375 /**
376  * g_buffered_input_stream_fill:
377  * @stream: a #GBufferedInputStream
378  * @count: the number of bytes that will be read from the stream
379  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore
380  * @error: location to store the error occurring, or %NULL to ignore
381  *
382  * Tries to read @count bytes from the stream into the buffer.
383  * Will block during this read.
384  *
385  * If @count is zero, returns zero and does nothing. A value of @count
386  * larger than %G_MAXSSIZE will cause a %G_IO_ERROR_INVALID_ARGUMENT error.
387  *
388  * On success, the number of bytes read into the buffer is returned.
389  * It is not an error if this is not the same as the requested size, as it
390  * can happen e.g. near the end of a file. Zero is returned on end of file
391  * (or if @count is zero),  but never otherwise.
392  *
393  * If @count is -1 then the attempted read size is equal to the number of
394  * bytes that are required to fill the buffer.
395  *
396  * If @cancellable is not %NULL, then the operation can be cancelled by
397  * triggering the cancellable object from another thread. If the operation
398  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. If an
399  * operation was partially finished when the operation was cancelled the
400  * partial result will be returned, without an error.
401  *
402  * On error -1 is returned and @error is set accordingly.
403  *
404  * For the asynchronous, non-blocking, version of this function, see
405  * g_buffered_input_stream_fill_async().
406  *
407  * Returns: the number of bytes read into @stream's buffer, up to @count,
408  *     or -1 on error.
409  */
410 gssize
411 g_buffered_input_stream_fill (GBufferedInputStream  *stream,
412                               gssize                 count,
413                               GCancellable          *cancellable,
414                               GError               **error)
415 {
416   GBufferedInputStreamClass *class;
417   GInputStream *input_stream;
418   gssize res;
419
420   g_return_val_if_fail (G_IS_BUFFERED_INPUT_STREAM (stream), -1);
421
422   input_stream = G_INPUT_STREAM (stream);
423
424   if (count < -1)
425     {
426       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
427                    _("Too large count value passed to %s"), G_STRFUNC);
428       return -1;
429     }
430
431   if (!g_input_stream_set_pending (input_stream, error))
432     return -1;
433
434   if (cancellable)
435     g_cancellable_push_current (cancellable);
436
437   class = G_BUFFERED_INPUT_STREAM_GET_CLASS (stream);
438   res = class->fill (stream, count, cancellable, error);
439
440   if (cancellable)
441     g_cancellable_pop_current (cancellable);
442
443   g_input_stream_clear_pending (input_stream);
444
445   return res;
446 }
447
448 static void
449 async_fill_callback_wrapper (GObject      *source_object,
450                              GAsyncResult *res,
451                              gpointer      user_data)
452 {
453   GBufferedInputStream *stream = G_BUFFERED_INPUT_STREAM (source_object);
454
455   g_input_stream_clear_pending (G_INPUT_STREAM (stream));
456   (*stream->priv->outstanding_callback) (source_object, res, user_data);
457   g_object_unref (stream);
458 }
459
460 /**
461  * g_buffered_input_stream_fill_async:
462  * @stream: a #GBufferedInputStream
463  * @count: the number of bytes that will be read from the stream
464  * @io_priority: the <link linkend="io-priority">I/O priority</link>
465  *     of the request
466  * @cancellable: (allow-none): optional #GCancellable object
467  * @callback: (scope async): a #GAsyncReadyCallback
468  * @user_data: (closure): a #gpointer
469  *
470  * Reads data into @stream's buffer asynchronously, up to @count size.
471  * @io_priority can be used to prioritize reads. For the synchronous
472  * version of this function, see g_buffered_input_stream_fill().
473  *
474  * If @count is -1 then the attempted read size is equal to the number
475  * of bytes that are required to fill the buffer.
476  */
477 void
478 g_buffered_input_stream_fill_async (GBufferedInputStream *stream,
479                                     gssize                count,
480                                     int                   io_priority,
481                                     GCancellable         *cancellable,
482                                     GAsyncReadyCallback   callback,
483                                     gpointer              user_data)
484 {
485   GBufferedInputStreamClass *class;
486   GSimpleAsyncResult *simple;
487   GError *error = NULL;
488
489   g_return_if_fail (G_IS_BUFFERED_INPUT_STREAM (stream));
490
491   if (count == 0)
492     {
493       simple = g_simple_async_result_new (G_OBJECT (stream),
494                                           callback,
495                                           user_data,
496                                           g_buffered_input_stream_fill_async);
497       g_simple_async_result_complete_in_idle (simple);
498       g_object_unref (simple);
499       return;
500     }
501
502   if (count < -1)
503     {
504       g_simple_async_report_error_in_idle (G_OBJECT (stream),
505                                            callback,
506                                            user_data,
507                                            G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
508                                            _("Too large count value passed to %s"),
509                                            G_STRFUNC);
510       return;
511     }
512
513   if (!g_input_stream_set_pending (G_INPUT_STREAM (stream), &error))
514     {
515       g_simple_async_report_take_gerror_in_idle (G_OBJECT (stream),
516                                             callback,
517                                             user_data,
518                                             error);
519       return;
520     }
521
522   class = G_BUFFERED_INPUT_STREAM_GET_CLASS (stream);
523
524   stream->priv->outstanding_callback = callback;
525   g_object_ref (stream);
526   class->fill_async (stream, count, io_priority, cancellable,
527                      async_fill_callback_wrapper, user_data);
528 }
529
530 /**
531  * g_buffered_input_stream_fill_finish:
532  * @stream: a #GBufferedInputStream
533  * @result: a #GAsyncResult
534  * @error: a #GError
535  *
536  * Finishes an asynchronous read.
537  *
538  * Returns: a #gssize of the read stream, or %-1 on an error.
539  */
540 gssize
541 g_buffered_input_stream_fill_finish (GBufferedInputStream  *stream,
542                                      GAsyncResult          *result,
543                                      GError               **error)
544 {
545   GBufferedInputStreamClass *class;
546
547   g_return_val_if_fail (G_IS_BUFFERED_INPUT_STREAM (stream), -1);
548   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), -1);
549
550   if (g_async_result_legacy_propagate_error (result, error))
551     return -1;
552   else if (g_async_result_is_tagged (result, g_buffered_input_stream_fill_async))
553     {
554       /* Special case read of 0 bytes */
555       return 0;
556     }
557
558   class = G_BUFFERED_INPUT_STREAM_GET_CLASS (stream);
559   return class->fill_finish (stream, result, error);
560 }
561
562 /**
563  * g_buffered_input_stream_get_available:
564  * @stream: #GBufferedInputStream
565  *
566  * Gets the size of the available data within the stream.
567  *
568  * Returns: size of the available stream.
569  */
570 gsize
571 g_buffered_input_stream_get_available (GBufferedInputStream *stream)
572 {
573   g_return_val_if_fail (G_IS_BUFFERED_INPUT_STREAM (stream), -1);
574
575   return stream->priv->end - stream->priv->pos;
576 }
577
578 /**
579  * g_buffered_input_stream_peek:
580  * @stream: a #GBufferedInputStream
581  * @buffer: (array length=count) (element-type guint8): a pointer to
582  *   an allocated chunk of memory
583  * @offset: a #gsize
584  * @count: a #gsize
585  *
586  * Peeks in the buffer, copying data of size @count into @buffer,
587  * offset @offset bytes.
588  *
589  * Returns: a #gsize of the number of bytes peeked, or -1 on error.
590  */
591 gsize
592 g_buffered_input_stream_peek (GBufferedInputStream *stream,
593                               void                 *buffer,
594                               gsize                 offset,
595                               gsize                 count)
596 {
597   gsize available;
598   gsize end;
599
600   g_return_val_if_fail (G_IS_BUFFERED_INPUT_STREAM (stream), -1);
601   g_return_val_if_fail (buffer != NULL, -1);
602
603   available = g_buffered_input_stream_get_available (stream);
604
605   if (offset > available)
606     return 0;
607
608   end = MIN (offset + count, available);
609   count = end - offset;
610
611   memcpy (buffer, stream->priv->buffer + stream->priv->pos + offset, count);
612   return count;
613 }
614
615 /**
616  * g_buffered_input_stream_peek_buffer:
617  * @stream: a #GBufferedInputStream
618  * @count: (out): a #gsize to get the number of bytes available in the buffer
619  *
620  * Returns the buffer with the currently available bytes. The returned
621  * buffer must not be modified and will become invalid when reading from
622  * the stream or filling the buffer.
623  *
624  * Returns: (array length=count) (element-type guint8) (transfer none):
625  *          read-only buffer
626  */
627 const void*
628 g_buffered_input_stream_peek_buffer (GBufferedInputStream *stream,
629                                      gsize                *count)
630 {
631   GBufferedInputStreamPrivate *priv;
632
633   g_return_val_if_fail (G_IS_BUFFERED_INPUT_STREAM (stream), NULL);
634
635   priv = stream->priv;
636
637   if (count)
638     *count = priv->end - priv->pos;
639
640   return priv->buffer + priv->pos;
641 }
642
643 static void
644 compact_buffer (GBufferedInputStream *stream)
645 {
646   GBufferedInputStreamPrivate *priv;
647   gsize current_size;
648
649   priv = stream->priv;
650
651   current_size = priv->end - priv->pos;
652
653   g_memmove (priv->buffer, priv->buffer + priv->pos, current_size);
654
655   priv->pos = 0;
656   priv->end = current_size;
657 }
658
659 static gssize
660 g_buffered_input_stream_real_fill (GBufferedInputStream  *stream,
661                                    gssize                 count,
662                                    GCancellable          *cancellable,
663                                    GError               **error)
664 {
665   GBufferedInputStreamPrivate *priv;
666   GInputStream *base_stream;
667   gssize nread;
668   gsize in_buffer;
669
670   priv = stream->priv;
671
672   if (count == -1)
673     count = priv->len;
674
675   in_buffer = priv->end - priv->pos;
676
677   /* Never fill more than can fit in the buffer */
678   count = MIN (count, priv->len - in_buffer);
679
680   /* If requested length does not fit at end, compact */
681   if (priv->len - priv->end < count)
682     compact_buffer (stream);
683
684   base_stream = G_FILTER_INPUT_STREAM (stream)->base_stream;
685   nread = g_input_stream_read (base_stream,
686                                priv->buffer + priv->end,
687                                count,
688                                cancellable,
689                                error);
690
691   if (nread > 0)
692     priv->end += nread;
693
694   return nread;
695 }
696
697 static gssize
698 g_buffered_input_stream_skip (GInputStream  *stream,
699                               gsize          count,
700                               GCancellable  *cancellable,
701                               GError       **error)
702 {
703   GBufferedInputStream        *bstream;
704   GBufferedInputStreamPrivate *priv;
705   GBufferedInputStreamClass *class;
706   GInputStream *base_stream;
707   gsize available, bytes_skipped;
708   gssize nread;
709
710   bstream = G_BUFFERED_INPUT_STREAM (stream);
711   priv = bstream->priv;
712
713   available = priv->end - priv->pos;
714
715   if (count <= available)
716     {
717       priv->pos += count;
718       return count;
719     }
720
721   /* Full request not available, skip all currently available and
722    * request refill for more
723    */
724
725   priv->pos = 0;
726   priv->end = 0;
727   bytes_skipped = available;
728   count -= available;
729
730   if (bytes_skipped > 0)
731     error = NULL; /* Ignore further errors if we already read some data */
732
733   if (count > priv->len)
734     {
735       /* Large request, shortcut buffer */
736
737       base_stream = G_FILTER_INPUT_STREAM (stream)->base_stream;
738
739       nread = g_input_stream_skip (base_stream,
740                                    count,
741                                    cancellable,
742                                    error);
743
744       if (nread < 0 && bytes_skipped == 0)
745         return -1;
746
747       if (nread > 0)
748         bytes_skipped += nread;
749
750       return bytes_skipped;
751     }
752
753   class = G_BUFFERED_INPUT_STREAM_GET_CLASS (stream);
754   nread = class->fill (bstream, priv->len, cancellable, error);
755
756   if (nread < 0)
757     {
758       if (bytes_skipped == 0)
759         return -1;
760       else
761         return bytes_skipped;
762     }
763
764   available = priv->end - priv->pos;
765   count = MIN (count, available);
766
767   bytes_skipped += count;
768   priv->pos += count;
769
770   return bytes_skipped;
771 }
772
773 static gssize
774 g_buffered_input_stream_read (GInputStream *stream,
775                               void         *buffer,
776                               gsize         count,
777                               GCancellable *cancellable,
778                               GError      **error)
779 {
780   GBufferedInputStream        *bstream;
781   GBufferedInputStreamPrivate *priv;
782   GBufferedInputStreamClass *class;
783   GInputStream *base_stream;
784   gsize available, bytes_read;
785   gssize nread;
786
787   bstream = G_BUFFERED_INPUT_STREAM (stream);
788   priv = bstream->priv;
789
790   available = priv->end - priv->pos;
791
792   if (count <= available)
793     {
794       memcpy (buffer, priv->buffer + priv->pos, count);
795       priv->pos += count;
796       return count;
797     }
798
799   /* Full request not available, read all currently available and
800    * request refill for more
801    */
802
803   memcpy (buffer, priv->buffer + priv->pos, available);
804   priv->pos = 0;
805   priv->end = 0;
806   bytes_read = available;
807   count -= available;
808
809   if (bytes_read > 0)
810     error = NULL; /* Ignore further errors if we already read some data */
811
812   if (count > priv->len)
813     {
814       /* Large request, shortcut buffer */
815
816       base_stream = G_FILTER_INPUT_STREAM (stream)->base_stream;
817
818       nread = g_input_stream_read (base_stream,
819                                    (char *)buffer + bytes_read,
820                                    count,
821                                    cancellable,
822                                    error);
823
824       if (nread < 0 && bytes_read == 0)
825         return -1;
826
827       if (nread > 0)
828         bytes_read += nread;
829
830       return bytes_read;
831     }
832
833   class = G_BUFFERED_INPUT_STREAM_GET_CLASS (stream);
834   nread = class->fill (bstream, priv->len, cancellable, error);
835   if (nread < 0)
836     {
837       if (bytes_read == 0)
838         return -1;
839       else
840         return bytes_read;
841     }
842
843   available = priv->end - priv->pos;
844   count = MIN (count, available);
845
846   memcpy ((char *)buffer + bytes_read, (char *)priv->buffer + priv->pos, count);
847   bytes_read += count;
848   priv->pos += count;
849
850   return bytes_read;
851 }
852
853 static goffset
854 g_buffered_input_stream_tell (GSeekable *seekable)
855 {
856   GBufferedInputStream        *bstream;
857   GBufferedInputStreamPrivate *priv;
858   GInputStream *base_stream;
859   GSeekable    *base_stream_seekable;
860   gsize available;
861   goffset base_offset;
862   
863   bstream = G_BUFFERED_INPUT_STREAM (seekable);
864   priv = bstream->priv;
865
866   base_stream = G_FILTER_INPUT_STREAM (seekable)->base_stream;
867   if (!G_IS_SEEKABLE (base_stream))
868     return 0;
869   base_stream_seekable = G_SEEKABLE (base_stream);
870   
871   available = priv->end - priv->pos;
872   base_offset = g_seekable_tell (base_stream_seekable);
873
874   return base_offset - available;
875 }
876
877 static gboolean
878 g_buffered_input_stream_can_seek (GSeekable *seekable)
879 {
880   GInputStream *base_stream;
881   
882   base_stream = G_FILTER_INPUT_STREAM (seekable)->base_stream;
883   return G_IS_SEEKABLE (base_stream) && g_seekable_can_seek (G_SEEKABLE (base_stream));
884 }
885
886 static gboolean
887 g_buffered_input_stream_seek (GSeekable     *seekable,
888                               goffset        offset,
889                               GSeekType      type,
890                               GCancellable  *cancellable,
891                               GError       **error)
892 {
893   GBufferedInputStream        *bstream;
894   GBufferedInputStreamPrivate *priv;
895   GInputStream *base_stream;
896   GSeekable *base_stream_seekable;
897
898   bstream = G_BUFFERED_INPUT_STREAM (seekable);
899   priv = bstream->priv;
900
901   base_stream = G_FILTER_INPUT_STREAM (seekable)->base_stream;
902   if (!G_IS_SEEKABLE (base_stream))
903     {
904       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
905                            _("Seek not supported on base stream"));
906       return FALSE;
907     }
908
909   base_stream_seekable = G_SEEKABLE (base_stream);
910   
911   if (type == G_SEEK_CUR)
912     {
913       if (offset <= priv->end - priv->pos && offset >= -priv->pos)
914         {
915           priv->pos += offset;
916           return TRUE;
917         }
918       else
919         {
920           offset -= priv->end - priv->pos;
921         }
922     }
923
924   if (g_seekable_seek (base_stream_seekable, offset, type, cancellable, error))
925     {
926       priv->pos = 0;
927       priv->end = 0;
928       return TRUE;
929     }
930   else
931     {
932       return FALSE;
933     }
934 }
935
936 static gboolean
937 g_buffered_input_stream_can_truncate (GSeekable *seekable)
938 {
939   return FALSE;
940 }
941
942 static gboolean
943 g_buffered_input_stream_truncate (GSeekable     *seekable,
944                                   goffset        offset,
945                                   GCancellable  *cancellable,
946                                   GError       **error)
947 {
948   g_set_error_literal (error,
949                        G_IO_ERROR,
950                        G_IO_ERROR_NOT_SUPPORTED,
951                        _("Cannot truncate GBufferedInputStream"));
952   return FALSE;
953 }
954
955 /**
956  * g_buffered_input_stream_read_byte:
957  * @stream: a #GBufferedInputStream
958  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore
959  * @error: location to store the error occurring, or %NULL to ignore
960  *
961  * Tries to read a single byte from the stream or the buffer. Will block
962  * during this read.
963  *
964  * On success, the byte read from the stream is returned. On end of stream
965  * -1 is returned but it's not an exceptional error and @error is not set.
966  *
967  * If @cancellable is not %NULL, then the operation can be cancelled by
968  * triggering the cancellable object from another thread. If the operation
969  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. If an
970  * operation was partially finished when the operation was cancelled the
971  * partial result will be returned, without an error.
972  *
973  * On error -1 is returned and @error is set accordingly.
974  *
975  * Returns: the byte read from the @stream, or -1 on end of stream or error.
976  */
977 int
978 g_buffered_input_stream_read_byte (GBufferedInputStream  *stream,
979                                    GCancellable          *cancellable,
980                                    GError               **error)
981 {
982   GBufferedInputStreamPrivate *priv;
983   GBufferedInputStreamClass *class;
984   GInputStream *input_stream;
985   gsize available;
986   gssize nread;
987
988   g_return_val_if_fail (G_IS_BUFFERED_INPUT_STREAM (stream), -1);
989
990   priv = stream->priv;
991   input_stream = G_INPUT_STREAM (stream);
992
993   if (g_input_stream_is_closed (input_stream))
994     {
995       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
996                            _("Stream is already closed"));
997       return -1;
998     }
999
1000   if (!g_input_stream_set_pending (input_stream, error))
1001     return -1;
1002
1003   available = priv->end - priv->pos;
1004
1005   if (available != 0)
1006     {
1007       g_input_stream_clear_pending (input_stream);
1008       return priv->buffer[priv->pos++];
1009     }
1010
1011   /* Byte not available, request refill for more */
1012
1013   if (cancellable)
1014     g_cancellable_push_current (cancellable);
1015
1016   priv->pos = 0;
1017   priv->end = 0;
1018
1019   class = G_BUFFERED_INPUT_STREAM_GET_CLASS (stream);
1020   nread = class->fill (stream, priv->len, cancellable, error);
1021
1022   if (cancellable)
1023     g_cancellable_pop_current (cancellable);
1024
1025   g_input_stream_clear_pending (input_stream);
1026
1027   if (nread <= 0)
1028     return -1; /* error or end of stream */
1029
1030   return priv->buffer[priv->pos++];
1031 }
1032
1033 /* ************************** */
1034 /* Async stuff implementation */
1035 /* ************************** */
1036
1037 static void
1038 fill_async_callback (GObject      *source_object,
1039                      GAsyncResult *result,
1040                      gpointer      user_data)
1041 {
1042   GError *error;
1043   gssize res;
1044   GSimpleAsyncResult *simple;
1045
1046   simple = user_data;
1047
1048   error = NULL;
1049   res = g_input_stream_read_finish (G_INPUT_STREAM (source_object),
1050                                     result, &error);
1051
1052   g_simple_async_result_set_op_res_gssize (simple, res);
1053   if (res == -1)
1054     {
1055       g_simple_async_result_take_error (simple, error);
1056     }
1057   else
1058     {
1059       GBufferedInputStreamPrivate *priv;
1060       GObject *object;
1061
1062       object = g_async_result_get_source_object (G_ASYNC_RESULT (simple));
1063       priv = G_BUFFERED_INPUT_STREAM (object)->priv;
1064
1065       g_assert_cmpint (priv->end + res, <=, priv->len);
1066       priv->end += res;
1067
1068       g_object_unref (object);
1069     }
1070
1071   /* Complete immediately, not in idle, since we're already
1072    * in a mainloop callout
1073    */
1074   g_simple_async_result_complete (simple);
1075   g_object_unref (simple);
1076 }
1077
1078 static void
1079 g_buffered_input_stream_real_fill_async (GBufferedInputStream *stream,
1080                                          gssize                count,
1081                                          int                   io_priority,
1082                                          GCancellable         *cancellable,
1083                                          GAsyncReadyCallback   callback,
1084                                          gpointer              user_data)
1085 {
1086   GBufferedInputStreamPrivate *priv;
1087   GInputStream *base_stream;
1088   GSimpleAsyncResult *simple;
1089   gsize in_buffer;
1090
1091   priv = stream->priv;
1092
1093   if (count == -1)
1094     count = priv->len;
1095
1096   in_buffer = priv->end - priv->pos;
1097
1098   /* Never fill more than can fit in the buffer */
1099   count = MIN (count, priv->len - in_buffer);
1100
1101   /* If requested length does not fit at end, compact */
1102   if (priv->len - priv->end < count)
1103     compact_buffer (stream);
1104
1105   simple = g_simple_async_result_new (G_OBJECT (stream),
1106                                       callback, user_data,
1107                                       g_buffered_input_stream_real_fill_async);
1108
1109   base_stream = G_FILTER_INPUT_STREAM (stream)->base_stream;
1110   g_input_stream_read_async (base_stream,
1111                              priv->buffer + priv->end,
1112                              count,
1113                              io_priority,
1114                              cancellable,
1115                              fill_async_callback,
1116                              simple);
1117 }
1118
1119 static gssize
1120 g_buffered_input_stream_real_fill_finish (GBufferedInputStream *stream,
1121                                           GAsyncResult         *result,
1122                                           GError              **error)
1123 {
1124   GSimpleAsyncResult *simple;
1125   gssize nread;
1126
1127   simple = G_SIMPLE_ASYNC_RESULT (result);
1128   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_buffered_input_stream_real_fill_async);
1129
1130   if (g_simple_async_result_propagate_error (simple, error))
1131     return -1;
1132
1133   nread = g_simple_async_result_get_op_res_gssize (simple);
1134   return nread;
1135 }
1136
1137 typedef struct
1138 {
1139   gssize bytes_skipped;
1140   gssize count;
1141 } SkipAsyncData;
1142
1143 static void
1144 free_skip_async_data (gpointer _data)
1145 {
1146   SkipAsyncData *data = _data;
1147   g_slice_free (SkipAsyncData, data);
1148 }
1149
1150 static void
1151 large_skip_callback (GObject      *source_object,
1152                      GAsyncResult *result,
1153                      gpointer      user_data)
1154 {
1155   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
1156   SkipAsyncData *data;
1157   GError *error;
1158   gssize nread;
1159
1160   data = g_simple_async_result_get_op_res_gpointer (simple);
1161
1162   error = NULL;
1163   nread = g_input_stream_skip_finish (G_INPUT_STREAM (source_object),
1164                                       result, &error);
1165
1166   /* Only report the error if we've not already read some data */
1167   if (nread < 0 && data->bytes_skipped == 0)
1168     g_simple_async_result_take_error (simple, error);
1169   else if (error)
1170     g_error_free (error);
1171
1172   if (nread > 0)
1173     data->bytes_skipped += nread;
1174
1175   /* Complete immediately, not in idle, since we're already
1176    * in a mainloop callout
1177    */
1178   g_simple_async_result_complete (simple);
1179   g_object_unref (simple);
1180 }
1181
1182 static void
1183 skip_fill_buffer_callback (GObject      *source_object,
1184                            GAsyncResult *result,
1185                            gpointer      user_data)
1186 {
1187   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
1188   GBufferedInputStream *bstream;
1189   GBufferedInputStreamPrivate *priv;
1190   SkipAsyncData *data;
1191   GError *error;
1192   gssize nread;
1193   gsize available;
1194
1195   bstream = G_BUFFERED_INPUT_STREAM (source_object);
1196   priv = bstream->priv;
1197
1198   data = g_simple_async_result_get_op_res_gpointer (simple);
1199
1200   error = NULL;
1201   nread = g_buffered_input_stream_fill_finish (bstream,
1202                                                result, &error);
1203
1204   if (nread < 0 && data->bytes_skipped == 0)
1205     g_simple_async_result_take_error (simple, error);
1206   else if (error)
1207     g_error_free (error);
1208
1209   if (nread > 0)
1210     {
1211       available = priv->end - priv->pos;
1212       data->count = MIN (data->count, available);
1213
1214       data->bytes_skipped += data->count;
1215       priv->pos += data->count;
1216     }
1217
1218   /* Complete immediately, not in idle, since we're already
1219    * in a mainloop callout
1220    */
1221   g_simple_async_result_complete (simple);
1222   g_object_unref (simple);
1223 }
1224
1225 static void
1226 g_buffered_input_stream_skip_async (GInputStream        *stream,
1227                                     gsize                count,
1228                                     int                  io_priority,
1229                                     GCancellable        *cancellable,
1230                                     GAsyncReadyCallback  callback,
1231                                     gpointer             user_data)
1232 {
1233   GBufferedInputStream *bstream;
1234   GBufferedInputStreamPrivate *priv;
1235   GBufferedInputStreamClass *class;
1236   GInputStream *base_stream;
1237   gsize available;
1238   GSimpleAsyncResult *simple;
1239   SkipAsyncData *data;
1240
1241   bstream = G_BUFFERED_INPUT_STREAM (stream);
1242   priv = bstream->priv;
1243
1244   data = g_slice_new (SkipAsyncData);
1245   data->bytes_skipped = 0;
1246   simple = g_simple_async_result_new (G_OBJECT (stream),
1247                                       callback, user_data,
1248                                       g_buffered_input_stream_skip_async);
1249   g_simple_async_result_set_op_res_gpointer (simple, data, free_skip_async_data);
1250
1251   available = priv->end - priv->pos;
1252
1253   if (count <= available)
1254     {
1255       priv->pos += count;
1256       data->bytes_skipped = count;
1257
1258       g_simple_async_result_complete_in_idle (simple);
1259       g_object_unref (simple);
1260       return;
1261     }
1262
1263   /* Full request not available, skip all currently available
1264    * and request refill for more
1265    */
1266
1267   priv->pos = 0;
1268   priv->end = 0;
1269
1270   count -= available;
1271
1272   data->bytes_skipped = available;
1273   data->count = count;
1274
1275   if (count > priv->len)
1276     {
1277       /* Large request, shortcut buffer */
1278
1279       base_stream = G_FILTER_INPUT_STREAM (stream)->base_stream;
1280
1281       g_input_stream_skip_async (base_stream,
1282                                  count,
1283                                  io_priority, cancellable,
1284                                  large_skip_callback,
1285                                  simple);
1286     }
1287   else
1288     {
1289       class = G_BUFFERED_INPUT_STREAM_GET_CLASS (stream);
1290       class->fill_async (bstream, priv->len, io_priority, cancellable,
1291                          skip_fill_buffer_callback, simple);
1292     }
1293 }
1294
1295 static gssize
1296 g_buffered_input_stream_skip_finish (GInputStream   *stream,
1297                                      GAsyncResult   *result,
1298                                      GError        **error)
1299 {
1300   GSimpleAsyncResult *simple;
1301   SkipAsyncData *data;
1302
1303   simple = G_SIMPLE_ASYNC_RESULT (result);
1304
1305   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_buffered_input_stream_skip_async);
1306
1307   data = g_simple_async_result_get_op_res_gpointer (simple);
1308
1309   return data->bytes_skipped;
1310 }