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