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