d528c133d27cc0f9ba880945e594cc90e491ac18
[platform/upstream/glib.git] / gio / gdatainputstream.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  * Copyright © 2009 Codethink Limited
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20  * Boston, MA 02111-1307, USA.
21  *
22  * Author: Alexander Larsson <alexl@redhat.com>
23  */
24
25 #include "config.h"
26 #include "gdatainputstream.h"
27 #include "gsimpleasyncresult.h"
28 #include "gcancellable.h"
29 #include "gioenumtypes.h"
30 #include "gioerror.h"
31 #include "glibintl.h"
32
33 #include <string.h>
34
35 /**
36  * SECTION:gdatainputstream
37  * @short_description: Data Input Stream
38  * @include: gio/gio.h
39  * @see_also: #GInputStream
40  * 
41  * Data input stream implements #GInputStream and includes functions for 
42  * reading structured data directly from a binary input stream.
43  *
44  **/
45
46 struct _GDataInputStreamPrivate {
47   GDataStreamByteOrder byte_order;
48   GDataStreamNewlineType newline_type;
49 };
50
51 enum {
52   PROP_0,
53   PROP_BYTE_ORDER,
54   PROP_NEWLINE_TYPE
55 };
56
57 static void g_data_input_stream_set_property (GObject      *object,
58                                               guint         prop_id,
59                                               const GValue *value,
60                                               GParamSpec   *pspec);
61 static void g_data_input_stream_get_property (GObject      *object,
62                                               guint         prop_id,
63                                               GValue       *value,
64                                               GParamSpec   *pspec);
65
66 G_DEFINE_TYPE (GDataInputStream,
67                g_data_input_stream,
68                G_TYPE_BUFFERED_INPUT_STREAM)
69
70
71 static void
72 g_data_input_stream_class_init (GDataInputStreamClass *klass)
73 {
74   GObjectClass *object_class;
75
76   g_type_class_add_private (klass, sizeof (GDataInputStreamPrivate));
77
78   object_class = G_OBJECT_CLASS (klass);
79   object_class->get_property = g_data_input_stream_get_property;
80   object_class->set_property = g_data_input_stream_set_property;
81
82   /**
83    * GDataStream:byte-order:
84    *
85    * The ::byte-order property determines the byte ordering that
86    * is used when reading multi-byte entities (such as integers)
87    * from the stream.
88    */ 
89   g_object_class_install_property (object_class,
90                                    PROP_BYTE_ORDER,
91                                    g_param_spec_enum ("byte-order",
92                                                       P_("Byte order"),
93                                                       P_("The byte order"),
94                                                       G_TYPE_DATA_STREAM_BYTE_ORDER,
95                                                       G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN,
96                                                       G_PARAM_READWRITE|G_PARAM_STATIC_NAME|G_PARAM_STATIC_BLURB));
97
98   /**
99    * GDataStream:newline-type:
100    *
101    * The :newline-type property determines what is considered
102    * as a line ending when reading complete lines from the stream.
103    */ 
104   g_object_class_install_property (object_class,
105                                    PROP_NEWLINE_TYPE,
106                                    g_param_spec_enum ("newline-type",
107                                                       P_("Newline type"),
108                                                       P_("The accepted types of line ending"),
109                                                       G_TYPE_DATA_STREAM_NEWLINE_TYPE,
110                                                       G_DATA_STREAM_NEWLINE_TYPE_LF,
111                                                       G_PARAM_READWRITE|G_PARAM_STATIC_NAME|G_PARAM_STATIC_BLURB));
112 }
113
114 static void
115 g_data_input_stream_set_property (GObject      *object,
116                                   guint         prop_id,
117                                   const GValue *value,
118                                   GParamSpec   *pspec)
119 {
120   GDataInputStream        *dstream;
121
122   dstream = G_DATA_INPUT_STREAM (object);
123
124    switch (prop_id)
125     {
126     case PROP_BYTE_ORDER:
127       g_data_input_stream_set_byte_order (dstream, g_value_get_enum (value));
128       break;
129
130     case PROP_NEWLINE_TYPE:
131       g_data_input_stream_set_newline_type (dstream, g_value_get_enum (value));
132       break;
133
134     default:
135       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
136       break;
137     }
138
139 }
140
141 static void
142 g_data_input_stream_get_property (GObject    *object,
143                                   guint       prop_id,
144                                   GValue     *value,
145                                   GParamSpec *pspec)
146 {
147   GDataInputStreamPrivate *priv;
148   GDataInputStream        *dstream;
149
150   dstream = G_DATA_INPUT_STREAM (object);
151   priv = dstream->priv;
152
153   switch (prop_id)
154     { 
155     case PROP_BYTE_ORDER:
156       g_value_set_enum (value, priv->byte_order);
157       break;
158
159     case PROP_NEWLINE_TYPE:
160       g_value_set_enum (value, priv->newline_type);
161       break;
162
163     default:
164       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
165       break;
166     }
167
168 }
169 static void
170 g_data_input_stream_init (GDataInputStream *stream)
171 {
172   stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (stream,
173                                               G_TYPE_DATA_INPUT_STREAM,
174                                               GDataInputStreamPrivate);
175
176   stream->priv->byte_order = G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN;
177   stream->priv->newline_type = G_DATA_STREAM_NEWLINE_TYPE_LF;
178 }
179
180 /**
181  * g_data_input_stream_new:
182  * @base_stream: a #GInputStream.
183  * 
184  * Creates a new data input stream for the @base_stream.
185  * 
186  * Returns: a new #GDataInputStream.
187  **/
188 GDataInputStream *
189 g_data_input_stream_new (GInputStream *base_stream)
190 {
191   GDataInputStream *stream;
192
193   g_return_val_if_fail (G_IS_INPUT_STREAM (base_stream), NULL);
194
195   stream = g_object_new (G_TYPE_DATA_INPUT_STREAM,
196                          "base-stream", base_stream,
197                          NULL);
198
199   return stream;
200 }
201
202 /**
203  * g_data_input_stream_set_byte_order:
204  * @stream: a given #GDataInputStream.
205  * @order: a #GDataStreamByteOrder to set.
206  * 
207  * This function sets the byte order for the given @stream. All subsequent
208  * reads from the @stream will be read in the given @order.
209  *  
210  **/
211 void
212 g_data_input_stream_set_byte_order (GDataInputStream     *stream,
213                                     GDataStreamByteOrder  order)
214 {
215   GDataInputStreamPrivate *priv;
216
217   g_return_if_fail (G_IS_DATA_INPUT_STREAM (stream));
218
219   priv = stream->priv;
220
221   if (priv->byte_order != order)
222     {
223       priv->byte_order = order;
224       
225       g_object_notify (G_OBJECT (stream), "byte-order");
226     }
227 }
228
229 /**
230  * g_data_input_stream_get_byte_order:
231  * @stream: a given #GDataInputStream.
232  * 
233  * Gets the byte order for the data input stream.
234  * 
235  * Returns: the @stream's current #GDataStreamByteOrder. 
236  **/
237 GDataStreamByteOrder
238 g_data_input_stream_get_byte_order (GDataInputStream *stream)
239 {
240   g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN);
241
242   return stream->priv->byte_order;
243 }
244
245 /**
246  * g_data_input_stream_set_newline_type:
247  * @stream: a #GDataInputStream.
248  * @type: the type of new line return as #GDataStreamNewlineType.
249  * 
250  * Sets the newline type for the @stream.
251  * 
252  * Note that using G_DATA_STREAM_NEWLINE_TYPE_ANY is slightly unsafe. If a read
253  * chunk ends in "CR" we must read an additional byte to know if this is "CR" or
254  * "CR LF", and this might block if there is no more data availible.
255  *  
256  **/
257 void
258 g_data_input_stream_set_newline_type (GDataInputStream       *stream,
259                                       GDataStreamNewlineType  type)
260 {
261   GDataInputStreamPrivate *priv;
262
263   g_return_if_fail (G_IS_DATA_INPUT_STREAM (stream));
264
265   priv = stream->priv;
266   
267   if (priv->newline_type != type)
268     {
269       priv->newline_type = type;
270
271       g_object_notify (G_OBJECT (stream), "newline-type");
272     }
273 }
274
275 /**
276  * g_data_input_stream_get_newline_type:
277  * @stream: a given #GDataInputStream.
278  * 
279  * Gets the current newline type for the @stream.
280  * 
281  * Returns: #GDataStreamNewlineType for the given @stream.
282  **/
283 GDataStreamNewlineType
284 g_data_input_stream_get_newline_type (GDataInputStream *stream)
285 {
286   g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), G_DATA_STREAM_NEWLINE_TYPE_ANY);
287
288   return stream->priv->newline_type;
289 }
290
291 static gboolean
292 read_data (GDataInputStream  *stream,
293            void              *buffer,
294            gsize              size,
295            GCancellable      *cancellable,
296            GError           **error)
297 {
298   gsize available;
299   gssize res;
300
301   while ((available = g_buffered_input_stream_get_available (G_BUFFERED_INPUT_STREAM (stream))) < size)
302     {
303       res = g_buffered_input_stream_fill (G_BUFFERED_INPUT_STREAM (stream),
304                                           size - available,
305                                           cancellable, error);
306       if (res < 0)
307         return FALSE;
308       if (res == 0)
309         {
310           g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
311                                _("Unexpected early end-of-stream"));
312           return FALSE;
313         }
314     }
315   
316   /* This should always succeed, since it's in the buffer */
317   res = g_input_stream_read (G_INPUT_STREAM (stream),
318                              buffer, size,
319                              NULL, NULL);
320   g_warn_if_fail (res == size);
321   return TRUE;
322 }
323
324
325 /**
326  * g_data_input_stream_read_byte:
327  * @stream: a given #GDataInputStream.
328  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
329  * @error: #GError for error reporting.
330  * 
331  * Reads an unsigned 8-bit/1-byte value from @stream.
332  *
333  * Returns: an unsigned 8-bit/1-byte value read from the @stream or %0 
334  * if an error occurred.
335  **/
336 guchar
337 g_data_input_stream_read_byte (GDataInputStream  *stream,
338                                GCancellable       *cancellable,
339                                GError            **error)
340 {
341   guchar c;
342   
343   g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), '\0');
344   
345   if (read_data (stream, &c, 1, cancellable, error))
346       return c;
347   
348   return 0;
349 }
350
351
352 /**
353  * g_data_input_stream_read_int16:
354  * @stream: a given #GDataInputStream.
355  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
356  * @error: #GError for error reporting.
357  * 
358  * Reads a 16-bit/2-byte value from @stream.
359  *
360  * In order to get the correct byte order for this read operation, 
361  * see g_data_input_stream_get_byte_order() and g_data_input_stream_set_byte_order().
362  * 
363  * Returns: a signed 16-bit/2-byte value read from @stream or %0 if 
364  * an error occurred.
365  **/
366 gint16
367 g_data_input_stream_read_int16 (GDataInputStream  *stream,
368                                GCancellable       *cancellable,
369                                GError            **error)
370 {
371   gint16 v;
372   
373   g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), 0);
374   
375   if (read_data (stream, &v, 2, cancellable, error))
376     {
377       switch (stream->priv->byte_order)
378         {
379         case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
380           v = GINT16_FROM_BE (v);
381           break;
382         case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
383           v = GINT16_FROM_LE (v);
384           break;
385         case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
386         default:
387           break;
388         }
389       return v;
390     }
391   
392   return 0;
393 }
394
395
396 /**
397  * g_data_input_stream_read_uint16:
398  * @stream: a given #GDataInputStream.
399  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
400  * @error: #GError for error reporting.
401  *
402  * Reads an unsigned 16-bit/2-byte value from @stream.
403  *
404  * In order to get the correct byte order for this read operation, 
405  * see g_data_input_stream_get_byte_order() and g_data_input_stream_set_byte_order(). 
406  * 
407  * Returns: an unsigned 16-bit/2-byte value read from the @stream or %0 if 
408  * an error occurred. 
409  **/
410 guint16
411 g_data_input_stream_read_uint16 (GDataInputStream  *stream,
412                                  GCancellable       *cancellable,
413                                  GError            **error)
414 {
415   guint16 v;
416   
417   g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), 0);
418   
419   if (read_data (stream, &v, 2, cancellable, error))
420     {
421       switch (stream->priv->byte_order)
422         {
423         case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
424           v = GUINT16_FROM_BE (v);
425           break;
426         case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
427           v = GUINT16_FROM_LE (v);
428           break;
429         case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
430         default:
431           break;
432         }
433       return v;
434     }
435   
436   return 0;
437 }
438
439
440 /**
441  * g_data_input_stream_read_int32:
442  * @stream: a given #GDataInputStream.
443  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
444  * @error: #GError for error reporting.
445  * 
446  * Reads a signed 32-bit/4-byte value from @stream.
447  *
448  * In order to get the correct byte order for this read operation, 
449  * see g_data_input_stream_get_byte_order() and g_data_input_stream_set_byte_order().
450  *
451  * If @cancellable is not %NULL, then the operation can be cancelled by
452  * triggering the cancellable object from another thread. If the operation
453  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. 
454  *   
455  * Returns: a signed 32-bit/4-byte value read from the @stream or %0 if 
456  * an error occurred. 
457  **/
458 gint32
459 g_data_input_stream_read_int32 (GDataInputStream  *stream,
460                                 GCancellable       *cancellable,
461                                 GError            **error)
462 {
463   gint32 v;
464   
465   g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), 0);
466   
467   if (read_data (stream, &v, 4, cancellable, error))
468     {
469       switch (stream->priv->byte_order)
470         {
471         case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
472           v = GINT32_FROM_BE (v);
473           break;
474         case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
475           v = GINT32_FROM_LE (v);
476           break;
477         case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
478         default:
479           break;
480         }
481       return v;
482     }
483   
484   return 0;
485 }
486
487
488 /**
489  * g_data_input_stream_read_uint32:
490  * @stream: a given #GDataInputStream.
491  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
492  * @error: #GError for error reporting.
493  * 
494  * Reads an unsigned 32-bit/4-byte value from @stream.
495  *
496  * In order to get the correct byte order for this read operation, 
497  * see g_data_input_stream_get_byte_order() and g_data_input_stream_set_byte_order().
498  *
499  * If @cancellable is not %NULL, then the operation can be cancelled by
500  * triggering the cancellable object from another thread. If the operation
501  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. 
502  * 
503  * Returns: an unsigned 32-bit/4-byte value read from the @stream or %0 if 
504  * an error occurred. 
505  **/
506 guint32
507 g_data_input_stream_read_uint32 (GDataInputStream  *stream,
508                                  GCancellable       *cancellable,
509                                  GError            **error)
510 {
511   guint32 v;
512   
513   g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), 0);
514   
515   if (read_data (stream, &v, 4, cancellable, error))
516     {
517       switch (stream->priv->byte_order)
518         {
519         case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
520           v = GUINT32_FROM_BE (v);
521           break;
522         case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
523           v = GUINT32_FROM_LE (v);
524           break;
525         case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
526         default:
527           break;
528         }
529       return v;
530     }
531   
532   return 0;
533 }
534
535
536 /**
537  * g_data_input_stream_read_int64:
538  * @stream: a given #GDataInputStream.
539  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
540  * @error: #GError for error reporting.
541  * 
542  * Reads a 64-bit/8-byte value from @stream.
543  *
544  * In order to get the correct byte order for this read operation, 
545  * see g_data_input_stream_get_byte_order() and g_data_input_stream_set_byte_order().
546  *
547  * If @cancellable is not %NULL, then the operation can be cancelled by
548  * triggering the cancellable object from another thread. If the operation
549  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. 
550  * 
551  * Returns: a signed 64-bit/8-byte value read from @stream or %0 if 
552  * an error occurred.  
553  **/
554 gint64
555 g_data_input_stream_read_int64 (GDataInputStream  *stream,
556                                GCancellable       *cancellable,
557                                GError            **error)
558 {
559   gint64 v;
560   
561   g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), 0);
562   
563   if (read_data (stream, &v, 8, cancellable, error))
564     {
565       switch (stream->priv->byte_order)
566         {
567         case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
568           v = GINT64_FROM_BE (v);
569           break;
570         case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
571           v = GINT64_FROM_LE (v);
572           break;
573         case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
574         default:
575           break;
576         }
577       return v;
578     }
579   
580   return 0;
581 }
582
583
584 /**
585  * g_data_input_stream_read_uint64:
586  * @stream: a given #GDataInputStream.
587  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
588  * @error: #GError for error reporting.
589  * 
590  * Reads an unsigned 64-bit/8-byte value from @stream.
591  *
592  * In order to get the correct byte order for this read operation, 
593  * see g_data_input_stream_get_byte_order().
594  *
595  * If @cancellable is not %NULL, then the operation can be cancelled by
596  * triggering the cancellable object from another thread. If the operation
597  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. 
598  * 
599  * Returns: an unsigned 64-bit/8-byte read from @stream or %0 if 
600  * an error occurred. 
601  **/
602 guint64
603 g_data_input_stream_read_uint64 (GDataInputStream  *stream,
604                                 GCancellable       *cancellable,
605                                 GError            **error)
606 {
607   guint64 v;
608   
609   g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), 0);
610   
611   if (read_data (stream, &v, 8, cancellable, error))
612     {
613       switch (stream->priv->byte_order)
614         {
615         case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
616           v = GUINT64_FROM_BE (v);
617           break;
618         case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
619           v = GUINT64_FROM_LE (v);
620           break;
621         case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
622         default:
623           break;
624         }
625       return v;
626     }
627   
628   return 0;
629 }
630
631 static gssize
632 scan_for_newline (GDataInputStream *stream,
633                   gsize            *checked_out,
634                   gboolean         *last_saw_cr_out,
635                   int              *newline_len_out)
636 {
637   GBufferedInputStream *bstream;
638   GDataInputStreamPrivate *priv;
639   const char *buffer;
640   gsize start, end, peeked;
641   int i;
642   gssize found_pos;
643   int newline_len;
644   gsize available, checked;
645   gboolean last_saw_cr;
646
647   priv = stream->priv;
648   
649   bstream = G_BUFFERED_INPUT_STREAM (stream);
650
651   checked = *checked_out;
652   last_saw_cr = *last_saw_cr_out;
653   found_pos = -1;
654   newline_len = 0;
655   
656   start = checked;
657   buffer = (const char*)g_buffered_input_stream_peek_buffer (bstream, &available) + start;
658   end = available;
659   peeked = end - start;
660
661   for (i = 0; checked < available && i < peeked; i++)
662     {
663       switch (priv->newline_type)
664         {
665         case G_DATA_STREAM_NEWLINE_TYPE_LF:
666           if (buffer[i] == 10)
667             {
668               found_pos = start + i;
669               newline_len = 1;
670             }
671           break;
672         case G_DATA_STREAM_NEWLINE_TYPE_CR:
673           if (buffer[i] == 13)
674             {
675               found_pos = start + i;
676               newline_len = 1;
677             }
678           break;
679         case G_DATA_STREAM_NEWLINE_TYPE_CR_LF:
680           if (last_saw_cr && buffer[i] == 10)
681             {
682               found_pos = start + i - 1;
683               newline_len = 2;
684             }
685           break;
686         default:
687         case G_DATA_STREAM_NEWLINE_TYPE_ANY:
688           if (buffer[i] == 10) /* LF */
689             {
690               if (last_saw_cr)
691                 {
692                   /* CR LF */
693                   found_pos = start + i - 1;
694                   newline_len = 2;
695                 }
696               else
697                 {
698                   /* LF */
699                   found_pos = start + i;
700                   newline_len = 1;
701                 }
702             }
703           else if (last_saw_cr)
704             {
705               /* Last was cr, this is not LF, end is CR */
706               found_pos = start + i - 1;
707               newline_len = 1;
708             }
709           /* Don't check for CR here, instead look at last_saw_cr on next byte */
710           break;
711         }
712         
713       last_saw_cr = (buffer[i] == 13);
714
715       if (found_pos != -1)
716         {
717           *newline_len_out = newline_len;
718           return found_pos;
719         }
720     }
721
722   checked = end;
723
724   *checked_out = checked;
725   *last_saw_cr_out = last_saw_cr;
726   return -1;
727 }
728                   
729
730 /**
731  * g_data_input_stream_read_line:
732  * @stream: a given #GDataInputStream.
733  * @length: (out): a #gsize to get the length of the data read in.
734  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
735  * @error: #GError for error reporting.
736  *
737  * Reads a line from the data input stream.  Note that no encoding
738  * checks or conversion is performed; the input is not guaranteed to
739  * be UTF-8, and may in fact have embedded NUL characters.
740  *
741  * If @cancellable is not %NULL, then the operation can be cancelled by
742  * triggering the cancellable object from another thread. If the operation
743  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
744  *
745  * Returns: (transfer full) (array zero-terminated=1) (element-type guint8): a
746  *  NUL terminated byte array with the line that was read in (without
747  *  the newlines).  Set @length to a #gsize to get the length of the
748  *  read line.  On an error, it will return %NULL and @error will be
749  *  set. If there's no content to read, it will still return %NULL,
750  *  but @error won't be set.
751  **/
752 char *
753 g_data_input_stream_read_line (GDataInputStream  *stream,
754                                gsize             *length,
755                                GCancellable      *cancellable,
756                                GError           **error)
757 {
758   GBufferedInputStream *bstream;
759   gsize checked;
760   gboolean last_saw_cr;
761   gssize found_pos;
762   gssize res;
763   int newline_len;
764   char *line;
765   
766   g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), NULL);  
767
768   bstream = G_BUFFERED_INPUT_STREAM (stream);
769
770   newline_len = 0;
771   checked = 0;
772   last_saw_cr = FALSE;
773
774   while ((found_pos = scan_for_newline (stream, &checked, &last_saw_cr, &newline_len)) == -1)
775     {
776       if (g_buffered_input_stream_get_available (bstream) ==
777           g_buffered_input_stream_get_buffer_size (bstream))
778         g_buffered_input_stream_set_buffer_size (bstream,
779                                                  2 * g_buffered_input_stream_get_buffer_size (bstream));
780
781       res = g_buffered_input_stream_fill (bstream, -1, cancellable, error);
782       if (res < 0)
783         return NULL;
784       if (res == 0)
785         {
786           /* End of stream */
787           if (g_buffered_input_stream_get_available (bstream) == 0)
788             {
789               if (length)
790                 *length = 0;
791               return NULL;
792             }
793           else
794             {
795               found_pos = checked;
796               newline_len = 0;
797               break;
798             }
799         }
800     }
801
802   line = g_malloc (found_pos + newline_len + 1);
803
804   res = g_input_stream_read (G_INPUT_STREAM (stream),
805                              line,
806                              found_pos + newline_len,
807                              NULL, NULL);
808   if (length)
809     *length = (gsize)found_pos;
810   g_warn_if_fail (res == found_pos + newline_len);
811   line[found_pos] = 0;
812   
813   return line;
814 }
815
816 static gssize
817 scan_for_chars (GDataInputStream *stream,
818                 gsize            *checked_out,
819                 const char       *stop_chars,
820                 gssize            stop_chars_len)
821 {
822   GBufferedInputStream *bstream;
823   const char *buffer;
824   gsize start, end, peeked;
825   int i;
826   gsize available, checked;
827   const char *stop_char;
828   const char *stop_end;
829
830   bstream = G_BUFFERED_INPUT_STREAM (stream);
831   stop_end = stop_chars + stop_chars_len;
832
833   checked = *checked_out;
834
835   start = checked;
836   buffer = (const char *)g_buffered_input_stream_peek_buffer (bstream, &available) + start;
837   end = available;
838   peeked = end - start;
839
840   for (i = 0; checked < available && i < peeked; i++)
841     {
842       for (stop_char = stop_chars; stop_char != stop_end; stop_char++)
843         {
844           if (buffer[i] == *stop_char)
845             return (start + i);
846         }
847     }
848
849   checked = end;
850
851   *checked_out = checked;
852   return -1;
853 }
854
855 /**
856  * g_data_input_stream_read_until:
857  * @stream: a given #GDataInputStream.
858  * @stop_chars: characters to terminate the read.
859  * @length: (out): a #gsize to get the length of the data read in.
860  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
861  * @error: #GError for error reporting.
862  *
863  * Reads a string from the data input stream, up to the first
864  * occurrence of any of the stop characters.
865  *
866  * Note that, in contrast to g_data_input_stream_read_until_async(),
867  * this function consumes the stop character that it finds.
868  *
869  * Don't use this function in new code.  Its functionality is
870  * inconsistent with g_data_input_stream_read_until_async().  Both
871  * functions will be marked as deprecated in a future release.  Use
872  * g_data_input_stream_read_upto() instead, but note that that function
873  * does not consume the stop character.
874  *
875  * Returns: (transfer full): a string with the data that was read
876  *     before encountering any of the stop characters. Set @length to
877  *     a #gsize to get the length of the string. This function will
878  *     return %NULL on an error.
879  */
880 char *
881 g_data_input_stream_read_until (GDataInputStream  *stream,
882                                const gchar        *stop_chars,
883                                gsize              *length,
884                                GCancellable       *cancellable,
885                                GError            **error)
886 {
887   GBufferedInputStream *bstream;
888   gchar *result;
889
890   bstream = G_BUFFERED_INPUT_STREAM (stream);
891
892   result = g_data_input_stream_read_upto (stream, stop_chars, -1,
893                                           length, cancellable, error);
894
895   /* If we're not at end of stream then we have a stop_char to consume. */
896   if (result != NULL && g_buffered_input_stream_get_available (bstream) > 0)
897     {
898       gsize res;
899       gchar b;
900
901       res = g_input_stream_read (G_INPUT_STREAM (stream), &b, 1, NULL, NULL);
902       g_assert (res == 1);
903     }
904
905   return result;
906 }
907
908 typedef struct
909 {
910   GDataInputStream *stream;
911   GSimpleAsyncResult *simple;
912   gboolean last_saw_cr;
913   gsize checked;
914   gint io_priority;
915   GCancellable *cancellable;
916
917   gchar *stop_chars;
918   gssize stop_chars_len;
919   gchar *line;
920   gsize length;
921 } GDataInputStreamReadData;
922
923 static void
924 g_data_input_stream_read_complete (GDataInputStreamReadData *data,
925                                    gsize                     read_length,
926                                    gsize                     skip_length,
927                                    gboolean                  need_idle_dispatch)
928 {
929   if (read_length || skip_length)
930     {
931       gssize bytes;
932
933       data->length = read_length;
934       data->line = g_malloc (read_length + 1);
935       data->line[read_length] = '\0';
936
937       /* we already checked the buffer.  this shouldn't fail. */
938       bytes = g_input_stream_read (G_INPUT_STREAM (data->stream),
939                                    data->line, read_length, NULL, NULL);
940       g_assert_cmpint (bytes, ==, read_length);
941
942       bytes = g_input_stream_skip (G_INPUT_STREAM (data->stream),
943                                    skip_length, NULL, NULL);
944       g_assert_cmpint (bytes, ==, skip_length);
945     }
946
947   if (need_idle_dispatch)
948     g_simple_async_result_complete_in_idle (data->simple);
949   else
950     g_simple_async_result_complete (data->simple);
951
952   g_object_unref (data->simple);
953 }
954
955 static void
956 g_data_input_stream_read_line_ready (GObject      *object,
957                                      GAsyncResult *result,
958                                      gpointer      user_data)
959 {
960   GDataInputStreamReadData *data = user_data;
961   gssize found_pos;
962   gint newline_len;
963
964   if (result)
965     /* this is a callback.  finish the async call. */
966     {
967       GBufferedInputStream *buffer = G_BUFFERED_INPUT_STREAM (data->stream);
968       GError *error = NULL;
969       gssize bytes;
970
971       bytes = g_buffered_input_stream_fill_finish (buffer, result, &error);
972
973       if (bytes <= 0)
974         {
975           if (bytes < 0)
976             /* stream error. */
977             {
978               g_simple_async_result_take_error (data->simple, error);
979               data->checked = 0;
980             }
981
982           g_data_input_stream_read_complete (data, data->checked, 0, FALSE);
983           return;
984         }
985
986       /* only proceed if we got more bytes... */
987     }
988
989   if (data->stop_chars)
990     {
991       found_pos = scan_for_chars (data->stream,
992                                   &data->checked,
993                                   data->stop_chars,
994                                   data->stop_chars_len);
995       newline_len = 0;
996     }
997   else
998     found_pos = scan_for_newline (data->stream, &data->checked,
999                                   &data->last_saw_cr, &newline_len);
1000
1001   if (found_pos == -1)
1002     /* didn't find a full line; need to buffer some more bytes */
1003     {
1004       GBufferedInputStream *buffer = G_BUFFERED_INPUT_STREAM (data->stream);
1005       gsize size;
1006
1007       size = g_buffered_input_stream_get_buffer_size (buffer);
1008
1009       if (g_buffered_input_stream_get_available (buffer) == size)
1010         /* need to grow the buffer */
1011         g_buffered_input_stream_set_buffer_size (buffer, size * 2);
1012
1013       /* try again */
1014       g_buffered_input_stream_fill_async (buffer, -1, data->io_priority,
1015                                           data->cancellable,
1016                                           g_data_input_stream_read_line_ready,
1017                                           user_data);
1018     }
1019   else
1020     {
1021       /* read the line and the EOL.  no error is possible. */
1022       g_data_input_stream_read_complete (data, found_pos,
1023                                          newline_len, result == NULL);
1024     }
1025 }
1026
1027 static void
1028 g_data_input_stream_read_data_free (gpointer user_data)
1029 {
1030   GDataInputStreamReadData *data = user_data;
1031
1032   /* we don't hold a ref to ->simple because it keeps a ref to us.
1033    * we are called because it is being finalized.
1034    */
1035
1036   g_free (data->stop_chars);
1037   if (data->cancellable)
1038     g_object_unref (data->cancellable);
1039   g_free (data->line);
1040   g_slice_free (GDataInputStreamReadData, data);
1041 }
1042
1043 static void
1044 g_data_input_stream_read_async (GDataInputStream    *stream,
1045                                 const gchar         *stop_chars,
1046                                 gssize               stop_chars_len,
1047                                 gint                 io_priority,
1048                                 GCancellable        *cancellable,
1049                                 GAsyncReadyCallback  callback,
1050                                 gpointer             user_data,
1051                                 gpointer             source_tag)
1052 {
1053   GDataInputStreamReadData *data;
1054
1055   data = g_slice_new (GDataInputStreamReadData);
1056   data->stream = stream;
1057   if (cancellable)
1058     g_object_ref (cancellable);
1059   data->cancellable = cancellable;
1060   if (stop_chars_len == -1)
1061     stop_chars_len = strlen (stop_chars);
1062   data->stop_chars = g_memdup (stop_chars, stop_chars_len);
1063   data->stop_chars_len = stop_chars_len;
1064   data->io_priority = io_priority;
1065   data->last_saw_cr = FALSE;
1066   data->checked = 0;
1067   data->line = NULL;
1068
1069   data->simple = g_simple_async_result_new (G_OBJECT (stream), callback,
1070                                             user_data, source_tag);
1071   g_simple_async_result_set_op_res_gpointer (data->simple, data,
1072                                              g_data_input_stream_read_data_free);
1073   g_data_input_stream_read_line_ready (NULL, NULL, data);
1074 }
1075
1076 static gchar *
1077 g_data_input_stream_read_finish (GDataInputStream  *stream,
1078                                  GAsyncResult      *result,
1079                                  gsize             *length,
1080                                  GError           **error)
1081 {
1082   GDataInputStreamReadData *data;
1083   GSimpleAsyncResult *simple;
1084   gchar *line;
1085
1086   simple = G_SIMPLE_ASYNC_RESULT (result);
1087
1088   if (g_simple_async_result_propagate_error (simple, error))
1089     return NULL;
1090
1091   data = g_simple_async_result_get_op_res_gpointer (simple);
1092
1093   line = data->line;
1094   data->line = NULL;
1095
1096   if (length && line)
1097     *length = data->length;
1098
1099   return line;
1100 }
1101
1102 /**
1103  * g_data_input_stream_read_line_async:
1104  * @stream: a given #GDataInputStream.
1105  * @io_priority: the <link linkend="io-priority">I/O priority</link>
1106  *     of the request.
1107  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
1108  * @callback: (scope async): callback to call when the request is satisfied.
1109  * @user_data: (closure): the data to pass to callback function.
1110  *
1111  * The asynchronous version of g_data_input_stream_read_line().  It is
1112  * an error to have two outstanding calls to this function.
1113  *
1114  * When the operation is finished, @callback will be called. You
1115  * can then call g_data_input_stream_read_line_finish() to get
1116  * the result of the operation.
1117  *
1118  * Since: 2.20
1119  */
1120 void
1121 g_data_input_stream_read_line_async (GDataInputStream    *stream,
1122                                      gint                 io_priority,
1123                                      GCancellable        *cancellable,
1124                                      GAsyncReadyCallback  callback,
1125                                      gpointer             user_data)
1126 {
1127   g_return_if_fail (G_IS_DATA_INPUT_STREAM (stream));
1128   g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1129
1130   g_data_input_stream_read_async (stream, NULL, 0, io_priority,
1131                                   cancellable, callback, user_data,
1132                                   g_data_input_stream_read_line_async);
1133 }
1134
1135 /**
1136  * g_data_input_stream_read_until_async:
1137  * @stream: a given #GDataInputStream.
1138  * @stop_chars: characters to terminate the read.
1139  * @io_priority: the <link linkend="io-priority">I/O priority</link>
1140  *     of the request.
1141  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
1142  * @callback: (scope async): callback to call when the request is satisfied.
1143  * @user_data: (closure): the data to pass to callback function.
1144  *
1145  * The asynchronous version of g_data_input_stream_read_until().
1146  * It is an error to have two outstanding calls to this function.
1147  *
1148  * Note that, in contrast to g_data_input_stream_read_until(),
1149  * this function does not consume the stop character that it finds.  You
1150  * must read it for yourself.
1151  *
1152  * When the operation is finished, @callback will be called. You
1153  * can then call g_data_input_stream_read_until_finish() to get
1154  * the result of the operation.
1155  *
1156  * Don't use this function in new code.  Its functionality is
1157  * inconsistent with g_data_input_stream_read_until().  Both functions
1158  * will be marked as deprecated in a future release.  Use
1159  * g_data_input_stream_read_upto_async() instead.
1160  *
1161  * Since: 2.20
1162  */
1163 void
1164 g_data_input_stream_read_until_async (GDataInputStream    *stream,
1165                                       const gchar         *stop_chars,
1166                                       gint                 io_priority,
1167                                       GCancellable        *cancellable,
1168                                       GAsyncReadyCallback  callback,
1169                                       gpointer             user_data)
1170 {
1171   g_return_if_fail (G_IS_DATA_INPUT_STREAM (stream));
1172   g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1173   g_return_if_fail (stop_chars != NULL);
1174
1175   g_data_input_stream_read_async (stream, stop_chars, -1, io_priority,
1176                                   cancellable, callback, user_data,
1177                                   g_data_input_stream_read_until_async);
1178 }
1179
1180 /**
1181  * g_data_input_stream_read_line_finish:
1182  * @stream: a given #GDataInputStream.
1183  * @result: the #GAsyncResult that was provided to the callback.
1184  * @length: (out): a #gsize to get the length of the data read in.
1185  * @error: #GError for error reporting.
1186  *
1187  * Finish an asynchronous call started by
1188  * g_data_input_stream_read_line_async().  Note the warning about
1189  * string encoding in g_data_input_stream_read_line() applies here as
1190  * well.
1191  *
1192  * Returns: (transfer full) (array zero-terminated=1) (element-type guint8):  a 
1193  *  NUL-terminated byte array with the line that was read in
1194  *  (without the newlines).  Set @length to a #gsize to get the
1195  *  length of the read line.  On an error, it will return %NULL and
1196  *  @error will be set. If there's no content to read, it will
1197  *  still return %NULL, but @error won't be set.
1198  *
1199  * Since: 2.20
1200  */
1201 gchar *
1202 g_data_input_stream_read_line_finish (GDataInputStream  *stream,
1203                                       GAsyncResult      *result,
1204                                       gsize             *length,
1205                                       GError           **error)
1206 {
1207   g_return_val_if_fail (
1208     g_simple_async_result_is_valid (result, G_OBJECT (stream),
1209       g_data_input_stream_read_line_async), NULL);
1210
1211   return g_data_input_stream_read_finish (stream, result, length, error);
1212 }
1213
1214 /**
1215  * g_data_input_stream_read_until_finish:
1216  * @stream: a given #GDataInputStream.
1217  * @result: the #GAsyncResult that was provided to the callback.
1218  * @length: (out): a #gsize to get the length of the data read in.
1219  * @error: #GError for error reporting.
1220  *
1221  * Finish an asynchronous call started by
1222  * g_data_input_stream_read_until_async().
1223  *
1224  * Since: 2.20
1225  *
1226  * Returns: (transfer full): a string with the data that was read
1227  *     before encountering any of the stop characters. Set @length to
1228  *     a #gsize to get the length of the string. This function will
1229  *     return %NULL on an error.
1230  */
1231 gchar *
1232 g_data_input_stream_read_until_finish (GDataInputStream  *stream,
1233                                        GAsyncResult      *result,
1234                                        gsize             *length,
1235                                        GError           **error)
1236 {
1237   g_return_val_if_fail (
1238     g_simple_async_result_is_valid (result, G_OBJECT (stream),
1239       g_data_input_stream_read_until_async), NULL);
1240
1241   return g_data_input_stream_read_finish (stream, result, length, error);
1242 }
1243
1244 /**
1245  * g_data_input_stream_read_upto:
1246  * @stream: a #GDataInputStream
1247  * @stop_chars: characters to terminate the read
1248  * @stop_chars_len: length of @stop_chars. May be -1 if @stop_chars is
1249  *     nul-terminated
1250  * @length: (out): a #gsize to get the length of the data read in
1251  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore
1252  * @error: #GError for error reporting
1253  *
1254  * Reads a string from the data input stream, up to the first
1255  * occurrence of any of the stop characters.
1256  *
1257  * In contrast to g_data_input_stream_read_until(), this function
1258  * does <emphasis>not</emphasis> consume the stop character. You have
1259  * to use g_data_input_stream_read_byte() to get it before calling
1260  * g_data_input_stream_read_upto() again.
1261  *
1262  * Note that @stop_chars may contain '\0' if @stop_chars_len is
1263  * specified.
1264  *
1265  * Returns: (transfer full): a string with the data that was read
1266  *     before encountering any of the stop characters. Set @length to
1267  *     a #gsize to get the length of the string. This function will
1268  *     return %NULL on an error
1269  *
1270  * Since: 2.26
1271  */
1272 char *
1273 g_data_input_stream_read_upto (GDataInputStream  *stream,
1274                                const gchar       *stop_chars,
1275                                gssize             stop_chars_len,
1276                                gsize             *length,
1277                                GCancellable      *cancellable,
1278                                GError           **error)
1279 {
1280   GBufferedInputStream *bstream;
1281   gsize checked;
1282   gssize found_pos;
1283   gssize res;
1284   char *data_until;
1285
1286   g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), NULL);
1287
1288   if (stop_chars_len < 0)
1289     stop_chars_len = strlen (stop_chars);
1290
1291   bstream = G_BUFFERED_INPUT_STREAM (stream);
1292
1293   checked = 0;
1294
1295   while ((found_pos = scan_for_chars (stream, &checked, stop_chars, stop_chars_len)) == -1)
1296     {
1297       if (g_buffered_input_stream_get_available (bstream) ==
1298           g_buffered_input_stream_get_buffer_size (bstream))
1299         g_buffered_input_stream_set_buffer_size (bstream,
1300                                                  2 * g_buffered_input_stream_get_buffer_size (bstream));
1301
1302       res = g_buffered_input_stream_fill (bstream, -1, cancellable, error);
1303       if (res < 0)
1304         return NULL;
1305       if (res == 0)
1306         {
1307           /* End of stream */
1308           if (g_buffered_input_stream_get_available (bstream) == 0)
1309             {
1310               if (length)
1311                 *length = 0;
1312               return NULL;
1313             }
1314           else
1315             {
1316               found_pos = checked;
1317               break;
1318             }
1319         }
1320     }
1321
1322   data_until = g_malloc (found_pos + 1);
1323
1324   res = g_input_stream_read (G_INPUT_STREAM (stream),
1325                              data_until,
1326                              found_pos,
1327                              NULL, NULL);
1328   if (length)
1329     *length = (gsize)found_pos;
1330   g_warn_if_fail (res == found_pos);
1331   data_until[found_pos] = 0;
1332
1333   return data_until;
1334 }
1335
1336 /**
1337  * g_data_input_stream_read_upto_async:
1338  * @stream: a #GDataInputStream
1339  * @stop_chars: characters to terminate the read
1340  * @stop_chars_len: length of @stop_chars. May be -1 if @stop_chars is
1341  *     nul-terminated
1342  * @io_priority: the <link linkend="io-priority">I/O priority</link>
1343  *     of the request.
1344  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore
1345  * @callback: (scope async): callback to call when the request is satisfied
1346  * @user_data: (closure): the data to pass to callback function
1347  *
1348  * The asynchronous version of g_data_input_stream_read_upto().
1349  * It is an error to have two outstanding calls to this function.
1350  *
1351  * In contrast to g_data_input_stream_read_until(), this function
1352  * does <emphasis>not</emphasis> consume the stop character. You have
1353  * to use g_data_input_stream_read_byte() to get it before calling
1354  * g_data_input_stream_read_upto() again.
1355  *
1356  * Note that @stop_chars may contain '\0' if @stop_chars_len is
1357  * specified.
1358  *
1359  * When the operation is finished, @callback will be called. You
1360  * can then call g_data_input_stream_read_upto_finish() to get
1361  * the result of the operation.
1362  *
1363  * Since: 2.26
1364  */
1365 void
1366 g_data_input_stream_read_upto_async (GDataInputStream    *stream,
1367                                      const gchar         *stop_chars,
1368                                      gssize               stop_chars_len,
1369                                      gint                 io_priority,
1370                                      GCancellable        *cancellable,
1371                                      GAsyncReadyCallback  callback,
1372                                      gpointer             user_data)
1373 {
1374   g_return_if_fail (G_IS_DATA_INPUT_STREAM (stream));
1375   g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1376   g_return_if_fail (stop_chars != NULL);
1377
1378   g_data_input_stream_read_async (stream, stop_chars, stop_chars_len, io_priority,
1379                                   cancellable, callback, user_data,
1380                                   g_data_input_stream_read_upto_async);
1381 }
1382
1383 /**
1384  * g_data_input_stream_read_upto_finish:
1385  * @stream: a #GDataInputStream
1386  * @result: the #GAsyncResult that was provided to the callback
1387  * @length: (out): a #gsize to get the length of the data read in
1388  * @error: #GError for error reporting
1389  *
1390  * Finish an asynchronous call started by
1391  * g_data_input_stream_read_upto_async().
1392  *
1393  * Note that this function does <emphasis>not</emphasis> consume the
1394  * stop character. You have to use g_data_input_stream_read_byte() to
1395  * get it before calling g_data_input_stream_read_upto_async() again.
1396  *
1397  * Returns: (transfer full): a string with the data that was read
1398  *     before encountering any of the stop characters. Set @length to
1399  *     a #gsize to get the length of the string. This function will
1400  *     return %NULL on an error.
1401  *
1402  * Since: 2.24
1403  */
1404 gchar *
1405 g_data_input_stream_read_upto_finish (GDataInputStream  *stream,
1406                                       GAsyncResult      *result,
1407                                       gsize             *length,
1408                                       GError           **error)
1409 {
1410   g_return_val_if_fail (
1411     g_simple_async_result_is_valid (result, G_OBJECT (stream),
1412       g_data_input_stream_read_upto_async), NULL);
1413
1414   return g_data_input_stream_read_finish (stream, result, length, error);
1415 }