gdatainputstream.c 43.9 KB
Newer Older
1 2 3
/* GIO - GLib Input, Output and Streaming Library
 * 
 * Copyright (C) 2006-2007 Red Hat, Inc.
4
 * Copyright (C) 2007 Jürg Billeter
5
 * Copyright © 2009 Codethink Limited
6 7 8 9
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11 12 13 14 15 16 17
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
18
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 20 21 22
 *
 * Author: Alexander Larsson <alexl@redhat.com>
 */

23
#include "config.h"
24
#include "gdatainputstream.h"
25
#include "gtask.h"
26
#include "gcancellable.h"
Matthias Clasen's avatar
Matthias Clasen committed
27
#include "gioenumtypes.h"
28
#include "gioerror.h"
29 30
#include "glibintl.h"

31
#include <string.h>
32

33 34
/**
 * SECTION:gdatainputstream
35
 * @short_description: Data Input Stream
Matthias Clasen's avatar
Matthias Clasen committed
36
 * @include: gio/gio.h
37
 * @see_also: #GInputStream
38 39
 * 
 * Data input stream implements #GInputStream and includes functions for 
40
 * reading structured data directly from a binary input stream.
41 42 43
 *
 **/

44 45 46 47 48 49
struct _GDataInputStreamPrivate {
  GDataStreamByteOrder byte_order;
  GDataStreamNewlineType newline_type;
};

enum {
Matthias Clasen's avatar
Matthias Clasen committed
50 51 52
  PROP_0,
  PROP_BYTE_ORDER,
  PROP_NEWLINE_TYPE
53 54 55 56 57 58 59 60 61 62 63
};

static void g_data_input_stream_set_property (GObject      *object,
					      guint         prop_id,
					      const GValue *value,
					      GParamSpec   *pspec);
static void g_data_input_stream_get_property (GObject      *object,
					      guint         prop_id,
					      GValue       *value,
					      GParamSpec   *pspec);

64 65 66
G_DEFINE_TYPE_WITH_PRIVATE (GDataInputStream,
                            g_data_input_stream,
                            G_TYPE_BUFFERED_INPUT_STREAM)
67 68 69 70 71 72 73 74 75 76


static void
g_data_input_stream_class_init (GDataInputStreamClass *klass)
{
  GObjectClass *object_class;

  object_class = G_OBJECT_CLASS (klass);
  object_class->get_property = g_data_input_stream_get_property;
  object_class->set_property = g_data_input_stream_set_property;
Matthias Clasen's avatar
Matthias Clasen committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

  /**
   * GDataStream:byte-order:
   *
   * The ::byte-order property determines the byte ordering that
   * is used when reading multi-byte entities (such as integers)
   * from the stream.
   */ 
  g_object_class_install_property (object_class,
                                   PROP_BYTE_ORDER,
                                   g_param_spec_enum ("byte-order",
                                                      P_("Byte order"),
                                                      P_("The byte order"),
                                                      G_TYPE_DATA_STREAM_BYTE_ORDER,
                                                      G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN,
                                                      G_PARAM_READWRITE|G_PARAM_STATIC_NAME|G_PARAM_STATIC_BLURB));

  /**
   * GDataStream:newline-type:
   *
   * The :newline-type property determines what is considered
   * as a line ending when reading complete lines from the stream.
   */ 
  g_object_class_install_property (object_class,
                                   PROP_NEWLINE_TYPE,
                                   g_param_spec_enum ("newline-type",
                                                      P_("Newline type"),
                                                      P_("The accepted types of line ending"),
                                                      G_TYPE_DATA_STREAM_NEWLINE_TYPE,
                                                      G_DATA_STREAM_NEWLINE_TYPE_LF,
                                                      G_PARAM_READWRITE|G_PARAM_STATIC_NAME|G_PARAM_STATIC_BLURB));
108 109 110
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
111 112 113 114
g_data_input_stream_set_property (GObject      *object,
				  guint         prop_id,
				  const GValue *value,
				  GParamSpec   *pspec)
115 116 117 118 119
{
  GDataInputStream        *dstream;

  dstream = G_DATA_INPUT_STREAM (object);

120
   switch (prop_id)
121
    {
Matthias Clasen's avatar
Matthias Clasen committed
122 123 124 125 126 127 128
    case PROP_BYTE_ORDER:
      g_data_input_stream_set_byte_order (dstream, g_value_get_enum (value));
      break;

    case PROP_NEWLINE_TYPE:
      g_data_input_stream_set_newline_type (dstream, g_value_get_enum (value));
      break;
129 130 131 132 133 134 135 136 137 138

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }

}

static void
g_data_input_stream_get_property (GObject    *object,
Matthias Clasen's avatar
Matthias Clasen committed
139 140 141
                                  guint       prop_id,
                                  GValue     *value,
                                  GParamSpec *pspec)
142 143 144 145 146 147 148 149 150
{
  GDataInputStreamPrivate *priv;
  GDataInputStream        *dstream;

  dstream = G_DATA_INPUT_STREAM (object);
  priv = dstream->priv;

  switch (prop_id)
    { 
Matthias Clasen's avatar
Matthias Clasen committed
151 152 153 154 155 156 157 158
    case PROP_BYTE_ORDER:
      g_value_set_enum (value, priv->byte_order);
      break;

    case PROP_NEWLINE_TYPE:
      g_value_set_enum (value, priv->newline_type);
      break;

159 160 161 162 163 164 165 166 167
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }

}
static void
g_data_input_stream_init (GDataInputStream *stream)
{
168
  stream->priv = g_data_input_stream_get_instance_private (stream);
169 170 171 172 173 174
  stream->priv->byte_order = G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN;
  stream->priv->newline_type = G_DATA_STREAM_NEWLINE_TYPE_LF;
}

/**
 * g_data_input_stream_new:
175 176 177
 * @base_stream: a #GInputStream.
 * 
 * Creates a new data input stream for the @base_stream.
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
 * 
 * Returns: a new #GDataInputStream.
 **/
GDataInputStream *
g_data_input_stream_new (GInputStream *base_stream)
{
  GDataInputStream *stream;

  g_return_val_if_fail (G_IS_INPUT_STREAM (base_stream), NULL);

  stream = g_object_new (G_TYPE_DATA_INPUT_STREAM,
                         "base-stream", base_stream,
                         NULL);

  return stream;
}

/**
 * g_data_input_stream_set_byte_order:
 * @stream: a given #GDataInputStream.
 * @order: a #GDataStreamByteOrder to set.
 * 
 * This function sets the byte order for the given @stream. All subsequent
 * reads from the @stream will be read in the given @order.
 *  
 **/
void
Matthias Clasen's avatar
Matthias Clasen committed
205 206
g_data_input_stream_set_byte_order (GDataInputStream     *stream,
				    GDataStreamByteOrder  order)
207
{
Matthias Clasen's avatar
Matthias Clasen committed
208 209
  GDataInputStreamPrivate *priv;

210 211
  g_return_if_fail (G_IS_DATA_INPUT_STREAM (stream));

Matthias Clasen's avatar
Matthias Clasen committed
212 213 214 215 216 217 218 219
  priv = stream->priv;

  if (priv->byte_order != order)
    {
      priv->byte_order = order;
      
      g_object_notify (G_OBJECT (stream), "byte-order");
    }
220 221 222 223 224 225
}

/**
 * g_data_input_stream_get_byte_order:
 * @stream: a given #GDataInputStream.
 * 
226 227
 * Gets the byte order for the data input stream.
 * 
Matthias Clasen's avatar
Matthias Clasen committed
228
 * Returns: the @stream's current #GDataStreamByteOrder. 
229 230 231 232 233 234 235 236 237 238 239
 **/
GDataStreamByteOrder
g_data_input_stream_get_byte_order (GDataInputStream *stream)
{
  g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN);

  return stream->priv->byte_order;
}

/**
 * g_data_input_stream_set_newline_type:
240
 * @stream: a #GDataInputStream.
241 242 243 244
 * @type: the type of new line return as #GDataStreamNewlineType.
 * 
 * Sets the newline type for the @stream.
 * 
245 246
 * Note that using G_DATA_STREAM_NEWLINE_TYPE_ANY is slightly unsafe. If a read
 * chunk ends in "CR" we must read an additional byte to know if this is "CR" or
Matthias Clasen's avatar
Matthias Clasen committed
247
 * "CR LF", and this might block if there is no more data available.
248 249 250
 *  
 **/
void
Matthias Clasen's avatar
Matthias Clasen committed
251 252
g_data_input_stream_set_newline_type (GDataInputStream       *stream,
				      GDataStreamNewlineType  type)
253
{
Matthias Clasen's avatar
Matthias Clasen committed
254 255
  GDataInputStreamPrivate *priv;

256 257
  g_return_if_fail (G_IS_DATA_INPUT_STREAM (stream));

Matthias Clasen's avatar
Matthias Clasen committed
258 259 260 261 262 263 264 265
  priv = stream->priv;
  
  if (priv->newline_type != type)
    {
      priv->newline_type = type;

      g_object_notify (G_OBJECT (stream), "newline-type");
    }
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
}

/**
 * g_data_input_stream_get_newline_type:
 * @stream: a given #GDataInputStream.
 * 
 * Gets the current newline type for the @stream.
 * 
 * Returns: #GDataStreamNewlineType for the given @stream.
 **/
GDataStreamNewlineType
g_data_input_stream_get_newline_type (GDataInputStream *stream)
{
  g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), G_DATA_STREAM_NEWLINE_TYPE_ANY);

  return stream->priv->newline_type;
}

static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
285 286 287 288 289
read_data (GDataInputStream  *stream,
           void              *buffer,
           gsize              size,
           GCancellable      *cancellable,
           GError           **error)
290 291 292 293 294 295 296 297 298 299 300 301 302
{
  gsize available;
  gssize res;

  while ((available = g_buffered_input_stream_get_available (G_BUFFERED_INPUT_STREAM (stream))) < size)
    {
      res = g_buffered_input_stream_fill (G_BUFFERED_INPUT_STREAM (stream),
					  size - available,
					  cancellable, error);
      if (res < 0)
	return FALSE;
      if (res == 0)
	{
303 304
	  g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                               _("Unexpected early end-of-stream"));
305 306 307 308
	  return FALSE;
	}
    }
  
309
  /* This should always succeed, since it's in the buffer */
310 311 312
  res = g_input_stream_read (G_INPUT_STREAM (stream),
			     buffer, size,
			     NULL, NULL);
313
  g_warn_if_fail (res == size);
314 315 316 317 318 319 320
  return TRUE;
}


/**
 * g_data_input_stream_read_byte:
 * @stream: a given #GDataInputStream.
321
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
322 323
 * @error: #GError for error reporting.
 * 
Matthias Clasen's avatar
Matthias Clasen committed
324 325
 * Reads an unsigned 8-bit/1-byte value from @stream.
 *
326
 * Returns: an unsigned 8-bit/1-byte value read from the @stream or `0`
327
 * if an error occurred.
328 329
 **/
guchar
Matthias Clasen's avatar
Matthias Clasen committed
330
g_data_input_stream_read_byte (GDataInputStream  *stream,
331 332
			       GCancellable       *cancellable,
			       GError            **error)
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
{
  guchar c;
  
  g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), '\0');
  
  if (read_data (stream, &c, 1, cancellable, error))
      return c;
  
  return 0;
}


/**
 * g_data_input_stream_read_int16:
 * @stream: a given #GDataInputStream.
348
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
349 350
 * @error: #GError for error reporting.
 * 
Matthias Clasen's avatar
Matthias Clasen committed
351 352
 * Reads a 16-bit/2-byte value from @stream.
 *
353
 * In order to get the correct byte order for this read operation, 
Christian Persch's avatar
Christian Persch committed
354
 * see g_data_input_stream_get_byte_order() and g_data_input_stream_set_byte_order().
355
 * 
356
 * Returns: a signed 16-bit/2-byte value read from @stream or `0` if
357
 * an error occurred.
358 359
 **/
gint16
Matthias Clasen's avatar
Matthias Clasen committed
360 361 362
g_data_input_stream_read_int16 (GDataInputStream  *stream,
			       GCancellable       *cancellable,
			       GError            **error)
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
{
  gint16 v;
  
  g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), 0);
  
  if (read_data (stream, &v, 2, cancellable, error))
    {
      switch (stream->priv->byte_order)
	{
	case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
	  v = GINT16_FROM_BE (v);
	  break;
	case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
	  v = GINT16_FROM_LE (v);
	  break;
	case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
	default:
	  break;
	}
      return v;
    }
  
  return 0;
}


/**
 * g_data_input_stream_read_uint16:
 * @stream: a given #GDataInputStream.
392
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
393 394
 * @error: #GError for error reporting.
 *
Matthias Clasen's avatar
Matthias Clasen committed
395 396
 * Reads an unsigned 16-bit/2-byte value from @stream.
 *
397
 * In order to get the correct byte order for this read operation, 
Christian Persch's avatar
Christian Persch committed
398
 * see g_data_input_stream_get_byte_order() and g_data_input_stream_set_byte_order(). 
399
 * 
400
 * Returns: an unsigned 16-bit/2-byte value read from the @stream or `0` if
401
 * an error occurred. 
402 403
 **/
guint16
Matthias Clasen's avatar
Matthias Clasen committed
404
g_data_input_stream_read_uint16 (GDataInputStream  *stream,
405 406
				 GCancellable       *cancellable,
				 GError            **error)
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
{
  guint16 v;
  
  g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), 0);
  
  if (read_data (stream, &v, 2, cancellable, error))
    {
      switch (stream->priv->byte_order)
	{
	case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
	  v = GUINT16_FROM_BE (v);
	  break;
	case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
	  v = GUINT16_FROM_LE (v);
	  break;
	case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
	default:
	  break;
	}
      return v;
    }
  
  return 0;
}


/**
 * g_data_input_stream_read_int32:
 * @stream: a given #GDataInputStream.
436
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
437 438
 * @error: #GError for error reporting.
 * 
Matthias Clasen's avatar
Matthias Clasen committed
439 440
 * Reads a signed 32-bit/4-byte value from @stream.
 *
441
 * In order to get the correct byte order for this read operation, 
Christian Persch's avatar
Christian Persch committed
442
 * see g_data_input_stream_get_byte_order() and g_data_input_stream_set_byte_order().
443 444 445 446
 *
 * If @cancellable is not %NULL, then the operation can be cancelled by
 * triggering the cancellable object from another thread. If the operation
 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. 
447
 *   
448
 * Returns: a signed 32-bit/4-byte value read from the @stream or `0` if
449
 * an error occurred. 
450 451
 **/
gint32
Matthias Clasen's avatar
Matthias Clasen committed
452
g_data_input_stream_read_int32 (GDataInputStream  *stream,
453 454
				GCancellable       *cancellable,
				GError            **error)
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
{
  gint32 v;
  
  g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), 0);
  
  if (read_data (stream, &v, 4, cancellable, error))
    {
      switch (stream->priv->byte_order)
	{
	case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
	  v = GINT32_FROM_BE (v);
	  break;
	case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
	  v = GINT32_FROM_LE (v);
	  break;
	case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
	default:
	  break;
	}
      return v;
    }
  
  return 0;
}


/**
 * g_data_input_stream_read_uint32:
 * @stream: a given #GDataInputStream.
484
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
485 486
 * @error: #GError for error reporting.
 * 
Matthias Clasen's avatar
Matthias Clasen committed
487 488
 * Reads an unsigned 32-bit/4-byte value from @stream.
 *
489
 * In order to get the correct byte order for this read operation, 
Christian Persch's avatar
Christian Persch committed
490
 * see g_data_input_stream_get_byte_order() and g_data_input_stream_set_byte_order().
491 492 493 494
 *
 * If @cancellable is not %NULL, then the operation can be cancelled by
 * triggering the cancellable object from another thread. If the operation
 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. 
495
 * 
496
 * Returns: an unsigned 32-bit/4-byte value read from the @stream or `0` if
497
 * an error occurred. 
498 499
 **/
guint32
Matthias Clasen's avatar
Matthias Clasen committed
500
g_data_input_stream_read_uint32 (GDataInputStream  *stream,
501 502
				 GCancellable       *cancellable,
				 GError            **error)
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
{
  guint32 v;
  
  g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), 0);
  
  if (read_data (stream, &v, 4, cancellable, error))
    {
      switch (stream->priv->byte_order)
	{
	case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
	  v = GUINT32_FROM_BE (v);
	  break;
	case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
	  v = GUINT32_FROM_LE (v);
	  break;
	case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
	default:
	  break;
	}
      return v;
    }
  
  return 0;
}


/**
 * g_data_input_stream_read_int64:
 * @stream: a given #GDataInputStream.
532
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
533 534
 * @error: #GError for error reporting.
 * 
Matthias Clasen's avatar
Matthias Clasen committed
535 536
 * Reads a 64-bit/8-byte value from @stream.
 *
537
 * In order to get the correct byte order for this read operation, 
Christian Persch's avatar
Christian Persch committed
538
 * see g_data_input_stream_get_byte_order() and g_data_input_stream_set_byte_order().
539 540 541 542
 *
 * If @cancellable is not %NULL, then the operation can be cancelled by
 * triggering the cancellable object from another thread. If the operation
 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. 
543
 * 
544
 * Returns: a signed 64-bit/8-byte value read from @stream or `0` if
545
 * an error occurred.  
546 547
 **/
gint64
Matthias Clasen's avatar
Matthias Clasen committed
548 549 550
g_data_input_stream_read_int64 (GDataInputStream  *stream,
			       GCancellable       *cancellable,
			       GError            **error)
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
{
  gint64 v;
  
  g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), 0);
  
  if (read_data (stream, &v, 8, cancellable, error))
    {
      switch (stream->priv->byte_order)
	{
	case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
	  v = GINT64_FROM_BE (v);
	  break;
	case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
	  v = GINT64_FROM_LE (v);
	  break;
	case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
	default:
	  break;
	}
      return v;
    }
  
  return 0;
}


/**
 * g_data_input_stream_read_uint64:
 * @stream: a given #GDataInputStream.
580
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
581 582
 * @error: #GError for error reporting.
 * 
Matthias Clasen's avatar
Matthias Clasen committed
583 584
 * Reads an unsigned 64-bit/8-byte value from @stream.
 *
585
 * In order to get the correct byte order for this read operation, 
Christian Persch's avatar
Christian Persch committed
586
 * see g_data_input_stream_get_byte_order().
587 588 589 590
 *
 * If @cancellable is not %NULL, then the operation can be cancelled by
 * triggering the cancellable object from another thread. If the operation
 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. 
591
 * 
592
 * Returns: an unsigned 64-bit/8-byte read from @stream or `0` if
593
 * an error occurred. 
594 595
 **/
guint64
Matthias Clasen's avatar
Matthias Clasen committed
596 597 598
g_data_input_stream_read_uint64 (GDataInputStream  *stream,
				GCancellable       *cancellable,
				GError            **error)
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
{
  guint64 v;
  
  g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), 0);
  
  if (read_data (stream, &v, 8, cancellable, error))
    {
      switch (stream->priv->byte_order)
	{
	case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
	  v = GUINT64_FROM_BE (v);
	  break;
	case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
	  v = GUINT64_FROM_LE (v);
	  break;
	case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
	default:
	  break;
	}
      return v;
    }
  
  return 0;
}

static gssize
scan_for_newline (GDataInputStream *stream,
Matthias Clasen's avatar
Matthias Clasen committed
626 627 628
		  gsize            *checked_out,
		  gboolean         *last_saw_cr_out,
		  int              *newline_len_out)
629 630 631
{
  GBufferedInputStream *bstream;
  GDataInputStreamPrivate *priv;
632
  const char *buffer;
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
  gsize start, end, peeked;
  int i;
  gssize found_pos;
  int newline_len;
  gsize available, checked;
  gboolean last_saw_cr;

  priv = stream->priv;
  
  bstream = G_BUFFERED_INPUT_STREAM (stream);

  checked = *checked_out;
  last_saw_cr = *last_saw_cr_out;
  found_pos = -1;
  newline_len = 0;
  
649
  start = checked;
Alexander Larsson's avatar
Alexander Larsson committed
650
  buffer = (const char*)g_buffered_input_stream_peek_buffer (bstream, &available) + start;
651 652
  end = available;
  peeked = end - start;
653

654 655 656
  for (i = 0; checked < available && i < peeked; i++)
    {
      switch (priv->newline_type)
657
	{
658 659
	case G_DATA_STREAM_NEWLINE_TYPE_LF:
	  if (buffer[i] == 10)
660
	    {
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
	      found_pos = start + i;
	      newline_len = 1;
	    }
	  break;
	case G_DATA_STREAM_NEWLINE_TYPE_CR:
	  if (buffer[i] == 13)
	    {
	      found_pos = start + i;
	      newline_len = 1;
	    }
	  break;
	case G_DATA_STREAM_NEWLINE_TYPE_CR_LF:
	  if (last_saw_cr && buffer[i] == 10)
	    {
	      found_pos = start + i - 1;
	      newline_len = 2;
	    }
	  break;
	default:
	case G_DATA_STREAM_NEWLINE_TYPE_ANY:
	  if (buffer[i] == 10) /* LF */
	    {
	      if (last_saw_cr)
684
		{
685
		  /* CR LF */
686 687 688
		  found_pos = start + i - 1;
		  newline_len = 2;
		}
689
	      else
690
		{
691 692
		  /* LF */
		  found_pos = start + i;
693 694 695
		  newline_len = 1;
		}
	    }
696
	  else if (last_saw_cr)
697
	    {
698 699 700
	      /* Last was cr, this is not LF, end is CR */
	      found_pos = start + i - 1;
	      newline_len = 1;
701
	    }
702 703 704 705 706 707 708 709 710 711
	  /* Don't check for CR here, instead look at last_saw_cr on next byte */
	  break;
	}
	
      last_saw_cr = (buffer[i] == 13);

      if (found_pos != -1)
	{
	  *newline_len_out = newline_len;
	  return found_pos;
712 713 714
	}
    }

715 716
  checked = end;

717 718 719 720 721 722 723 724 725
  *checked_out = checked;
  *last_saw_cr_out = last_saw_cr;
  return -1;
}
		  

/**
 * g_data_input_stream_read_line:
 * @stream: a given #GDataInputStream.
726
 * @length: (out) (optional): a #gsize to get the length of the data read in.
727
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
728
 * @error: #GError for error reporting.
729
 *
730 731 732
 * Reads a line from the data input stream.  Note that no encoding
 * checks or conversion is performed; the input is not guaranteed to
 * be UTF-8, and may in fact have embedded NUL characters.
Matthias Clasen's avatar
Matthias Clasen committed
733
 *
734 735
 * If @cancellable is not %NULL, then the operation can be cancelled by
 * triggering the cancellable object from another thread. If the operation
Matthias Clasen's avatar
Matthias Clasen committed
736 737
 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
 *
738 739 740 741 742 743
 * Returns: (nullable) (transfer full) (array zero-terminated=1) (element-type guint8):
 *  a NUL terminated byte array with the line that was read in
 *  (without the newlines).  Set @length to a #gsize to get the length
 *  of the read line.  On an error, it will return %NULL and @error
 *  will be set. If there's no content to read, it will still return
 *  %NULL, but @error won't be set.
744 745
 **/
char *
Matthias Clasen's avatar
Matthias Clasen committed
746 747 748 749
g_data_input_stream_read_line (GDataInputStream  *stream,
			       gsize             *length,
			       GCancellable      *cancellable,
			       GError           **error)
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
{
  GBufferedInputStream *bstream;
  gsize checked;
  gboolean last_saw_cr;
  gssize found_pos;
  gssize res;
  int newline_len;
  char *line;
  
  g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), NULL);  

  bstream = G_BUFFERED_INPUT_STREAM (stream);

  newline_len = 0;
  checked = 0;
  last_saw_cr = FALSE;

  while ((found_pos = scan_for_newline (stream, &checked, &last_saw_cr, &newline_len)) == -1)
    {
      if (g_buffered_input_stream_get_available (bstream) ==
	  g_buffered_input_stream_get_buffer_size (bstream))
	g_buffered_input_stream_set_buffer_size (bstream,
						 2 * g_buffered_input_stream_get_buffer_size (bstream));

      res = g_buffered_input_stream_fill (bstream, -1, cancellable, error);
      if (res < 0)
	return NULL;
      if (res == 0)
	{
	  /* End of stream */
	  if (g_buffered_input_stream_get_available (bstream) == 0)
	    {
	      if (length)
		*length = 0;
	      return NULL;
	    }
	  else
	    {
	      found_pos = checked;
	      newline_len = 0;
	      break;
	    }
	}
    }

  line = g_malloc (found_pos + newline_len + 1);

  res = g_input_stream_read (G_INPUT_STREAM (stream),
			     line,
			     found_pos + newline_len,
			     NULL, NULL);
  if (length)
    *length = (gsize)found_pos;
803
  g_warn_if_fail (res == found_pos + newline_len);
804
  line[found_pos] = 0;
805 806 807 808
  
  return line;
}

809 810 811
/**
 * g_data_input_stream_read_line_utf8:
 * @stream: a given #GDataInputStream.
812
 * @length: (out) (optional): a #gsize to get the length of the data read in.
813
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
814 815 816 817 818 819 820 821
 * @error: #GError for error reporting.
 *
 * Reads a UTF-8 encoded line from the data input stream.
 *
 * If @cancellable is not %NULL, then the operation can be cancelled by
 * triggering the cancellable object from another thread. If the operation
 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
 *
822 823 824 825 826 827 828
 * Returns: (nullable) (transfer full): a NUL terminated UTF-8 string
 *  with the line that was read in (without the newlines).  Set
 *  @length to a #gsize to get the length of the read line.  On an
 *  error, it will return %NULL and @error will be set.  For UTF-8
 *  conversion errors, the set error domain is %G_CONVERT_ERROR.  If
 *  there's no content to read, it will still return %NULL, but @error
 *  won't be set.
829 830
 *
 * Since: 2.30
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
 **/
char *
g_data_input_stream_read_line_utf8 (GDataInputStream  *stream,
				    gsize             *length,
				    GCancellable      *cancellable,
				    GError           **error)
{
  char *res;

  res = g_data_input_stream_read_line (stream, length, cancellable, error);
  if (!res)
    return NULL;
  
  if (!g_utf8_validate (res, -1, NULL))
    {
      g_set_error_literal (error, G_CONVERT_ERROR,
			   G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
			   _("Invalid byte sequence in conversion input"));
      g_free (res);
      return NULL;
    }
  return res;
}

855 856
static gssize
scan_for_chars (GDataInputStream *stream,
Matthias Clasen's avatar
Matthias Clasen committed
857
		gsize            *checked_out,
858 859
		const char       *stop_chars,
                gssize            stop_chars_len)
860 861 862 863 864 865 866
{
  GBufferedInputStream *bstream;
  const char *buffer;
  gsize start, end, peeked;
  int i;
  gsize available, checked;
  const char *stop_char;
867
  const char *stop_end;
868 869

  bstream = G_BUFFERED_INPUT_STREAM (stream);
870
  stop_end = stop_chars + stop_chars_len;
871 872

  checked = *checked_out;
873

874
  start = checked;
Alexander Larsson's avatar
Alexander Larsson committed
875
  buffer = (const char *)g_buffered_input_stream_peek_buffer (bstream, &available) + start;
876 877 878 879 880
  end = available;
  peeked = end - start;

  for (i = 0; checked < available && i < peeked; i++)
    {
881
      for (stop_char = stop_chars; stop_char != stop_end; stop_char++)
882 883 884 885 886 887 888 889 890 891 892 893
	{
	  if (buffer[i] == *stop_char)
	    return (start + i);
	}
    }

  checked = end;

  *checked_out = checked;
  return -1;
}

894 895 896
/**
 * g_data_input_stream_read_until:
 * @stream: a given #GDataInputStream.
897
 * @stop_chars: characters to terminate the read.
898
 * @length: (out) (optional): a #gsize to get the length of the data read in.
899
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
900
 * @error: #GError for error reporting.
Matthias Clasen's avatar
Matthias Clasen committed
901 902
 *
 * Reads a string from the data input stream, up to the first
903
 * occurrence of any of the stop characters.
Matthias Clasen's avatar
Matthias Clasen committed
904
 *
905 906 907
 * Note that, in contrast to g_data_input_stream_read_until_async(),
 * this function consumes the stop character that it finds.
 *
908 909 910 911 912 913
 * Don't use this function in new code.  Its functionality is
 * inconsistent with g_data_input_stream_read_until_async().  Both
 * functions will be marked as deprecated in a future release.  Use
 * g_data_input_stream_read_upto() instead, but note that that function
 * does not consume the stop character.
 *
914 915 916 917
 * Returns: (transfer full): a string with the data that was read
 *     before encountering any of the stop characters. Set @length to
 *     a #gsize to get the length of the string. This function will
 *     return %NULL on an error.
918 919
 * Deprecated: 2.56: Use g_data_input_stream_read_upto() instead, which has more
 *     consistent behaviour regarding the stop character.
Matthias Clasen's avatar
Matthias Clasen committed
920
 */
921
char *
Matthias Clasen's avatar
Matthias Clasen committed
922 923 924 925 926
g_data_input_stream_read_until (GDataInputStream  *stream,
			       const gchar        *stop_chars,
			       gsize              *length,
			       GCancellable       *cancellable,
			       GError            **error)
927
{
928
  GBufferedInputStream *bstream;
929
  gchar *result;
930 931 932

  bstream = G_BUFFERED_INPUT_STREAM (stream);

933 934
  result = g_data_input_stream_read_upto (stream, stop_chars, -1,
                                          length, cancellable, error);
935

936 937
  /* If we're not at end of stream then we have a stop_char to consume. */
  if (result != NULL && g_buffered_input_stream_get_available (bstream) > 0)
938
    {
939
      gsize res G_GNUC_UNUSED  /* when compiling with G_DISABLE_ASSERT */;
940
      gchar b;
941

942 943
      res = g_input_stream_read (G_INPUT_STREAM (stream), &b, 1, NULL, NULL);
      g_assert (res == 1);
944 945
    }

946
  return result;
947
}
948

949 950 951 952 953 954
typedef struct
{
  gboolean last_saw_cr;
  gsize checked;

  gchar *stop_chars;
955
  gssize stop_chars_len;
956 957 958 959
  gsize length;
} GDataInputStreamReadData;

static void
960 961 962
g_data_input_stream_read_complete (GTask *task,
                                   gsize  read_length,
                                   gsize  skip_length)
963
{
964 965 966 967
  GDataInputStreamReadData *data = g_task_get_task_data (task);
  GInputStream *stream = g_task_get_source_object (task);
  char *line = NULL;

968 969 970 971 972
  if (read_length || skip_length)
    {
      gssize bytes;

      data->length = read_length;
973 974
      line = g_malloc (read_length + 1);
      line[read_length] = '\0';
975 976

      /* we already checked the buffer.  this shouldn't fail. */
977
      bytes = g_input_stream_read (stream, line, read_length, NULL, NULL);
978 979
      g_assert_cmpint (bytes, ==, read_length);

980
      bytes = g_input_stream_skip (stream, skip_length, NULL, NULL);
981 982 983
      g_assert_cmpint (bytes, ==, skip_length);
    }

984 985
  g_task_return_pointer (task, line, g_free);
  g_object_unref (task);
986 987 988 989 990 991 992
}

static void
g_data_input_stream_read_line_ready (GObject      *object,
                                     GAsyncResult *result,
                                     gpointer      user_data)
{
993 994 995
  GTask *task = user_data;
  GDataInputStreamReadData *data = g_task_get_task_data (task);
  GBufferedInputStream *buffer = g_task_get_source_object (task);
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
  gssize found_pos;
  gint newline_len;

  if (result)
    /* this is a callback.  finish the async call. */
    {
      GError *error = NULL;
      gssize bytes;

      bytes = g_buffered_input_stream_fill_finish (buffer, result, &error);

      if (bytes <= 0)
        {
          if (bytes < 0)
            /* stream error. */
            {
1012 1013 1014
              g_task_return_error (task, error);
              g_object_unref (task);
              return;
1015 1016
            }

1017
          g_data_input_stream_read_complete (task, data->checked, 0);
1018 1019 1020 1021 1022 1023 1024 1025
          return;
        }

      /* only proceed if we got more bytes... */
    }

  if (data->stop_chars)
    {
1026
      found_pos = scan_for_chars (G_DATA_INPUT_STREAM (buffer),
1027
                                  &data->checked,
1028 1029
                                  data->stop_chars,
                                  data->stop_chars_len);
1030 1031 1032
      newline_len = 0;
    }
  else
1033
    found_pos = scan_for_newline (G_DATA_INPUT_STREAM (buffer), &data->checked,
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
                                  &data->last_saw_cr, &newline_len);

  if (found_pos == -1)
    /* didn't find a full line; need to buffer some more bytes */
    {
      gsize size;

      size = g_buffered_input_stream_get_buffer_size (buffer);

      if (g_buffered_input_stream_get_available (buffer) == size)
        /* need to grow the buffer */
        g_buffered_input_stream_set_buffer_size (buffer, size * 2);

      /* try again */
1048 1049 1050
      g_buffered_input_stream_fill_async (buffer, -1,
                                          g_task_get_priority (task),
                                          g_task_get_cancellable (task),
1051 1052 1053 1054 1055 1056
                                          g_data_input_stream_read_line_ready,
                                          user_data);
    }
  else
    {
      /* read the line and the EOL.  no error is possible. */
1057
      g_data_input_stream_read_complete (task, found_pos, newline_len);
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
    }
}

static void
g_data_input_stream_read_data_free (gpointer user_data)
{
  GDataInputStreamReadData *data = user_data;

  g_free (data->stop_chars);
  g_slice_free (GDataInputStreamReadData, data);
}

static void
g_data_input_stream_read_async (GDataInputStream    *stream,
                                const gchar         *stop_chars,
1073
                                gssize               stop_chars_len,
1074 1075 1076
                                gint                 io_priority,
                                GCancellable        *cancellable,
                                GAsyncReadyCallback  callback,
1077
                                gpointer             user_data)
1078 1079
{
  GDataInputStreamReadData *data;
1080
  GTask *task;
1081

1082
  data = g_slice_new0 (GDataInputStreamReadData);
1083 1084 1085 1086
  if (stop_chars_len == -1)
    stop_chars_len = strlen (stop_chars);
  data->stop_chars = g_memdup (stop_chars, stop_chars_len);
  data->stop_chars_len = stop_chars_len;
1087
  data->last_saw_cr = FALSE;
1088 1089

  task = g_task_new (stream, cancellable, callback, user_data);
1090
  g_task_set_source_tag (task, g_data_input_stream_read_async);
1091 1092 1093 1094
  g_task_set_task_data (task, data, g_data_input_stream_read_data_free);
  g_task_set_priority (task, io_priority);

  g_data_input_stream_read_line_ready (NULL, NULL, task);
1095 1096 1097 1098 1099 1100 1101 1102
}

static gchar *
g_data_input_stream_read_finish (GDataInputStream  *stream,
                                 GAsyncResult      *result,
                                 gsize             *length,
                                 GError           **error)
{
1103
  GTask *task = G_TASK (result);
1104 1105
  gchar *line;

1106
  line = g_task_propagate_pointer (task, error);
1107 1108

  if (length && line)
1109 1110 1111 1112 1113
    {
      GDataInputStreamReadData *data = g_task_get_task_data (task);

      *length = data->length;
    }
1114 1115 1116 1117 1118 1119 1120

  return line;
}

/**
 * g_data_input_stream_read_line_async:
 * @stream: a given #GDataInputStream.
1121
 * @io_priority: the [I/O priority][io-priority] of the request
1122
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
1123 1124
 * @callback: (scope async): callback to call when the request is satisfied.
 * @user_data: (closure): the data to pass to callback function.
1125 1126 1127
 *
 * The asynchronous version of g_data_input_stream_read_line().  It is
 * an error to have two outstanding calls to this function.
Matthias Clasen's avatar
Matthias Clasen committed
1128
 *
Matthias Clasen's avatar
Matthias Clasen committed
1129 1130 1131 1132
 * When the operation is finished, @callback will be called. You
 * can then call g_data_input_stream_read_line_finish() to get
 * the result of the operation.
 *
Matthias Clasen's avatar
Matthias Clasen committed
1133 1134
 * Since: 2.20
 */
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
void
g_data_input_stream_read_line_async (GDataInputStream    *stream,
                                     gint                 io_priority,
                                     GCancellable        *cancellable,
                                     GAsyncReadyCallback  callback,
                                     gpointer             user_data)
{
  g_return_if_fail (G_IS_DATA_INPUT_STREAM (stream));
  g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));

1145
  g_data_input_stream_read_async (stream, NULL, 0, io_priority,
1146
                                  cancellable, callback, user_data);
1147 1148 1149 1150 1151 1152
}

/**
 * g_data_input_stream_read_until_async:
 * @stream: a given #GDataInputStream.
 * @stop_chars: characters to terminate the read.
1153
 * @io_priority: the [I/O priority][io-priority] of the request
1154
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
1155 1156
 * @callback: (scope async): callback to call when the request is satisfied.
 * @user_data: (closure): the data to pass to callback function.
1157
 *
Matthias Clasen's avatar
Matthias Clasen committed
1158 1159 1160
 * The asynchronous version of g_data_input_stream_read_until().
 * It is an error to have two outstanding calls to this function.
 *
1161 1162 1163 1164
 * Note that, in contrast to g_data_input_stream_read_until(),
 * this function does not consume the stop character that it finds.  You
 * must read it for yourself.
 *
Matthias Clasen's avatar
Matthias Clasen committed
1165 1166 1167 1168
 * When the operation is finished, @callback will be called. You
 * can then call g_data_input_stream_read_until_finish() to get
 * the result of the operation.
 *
1169 1170 1171 1172 1173
 * Don't use this function in new code.  Its functionality is
 * inconsistent with g_data_input_stream_read_until().  Both functions
 * will be marked as deprecated in a future release.  Use
 * g_data_input_stream_read_upto_async() instead.
 *
Matthias Clasen's avatar
Matthias Clasen committed
1174
 * Since: 2.20
1175 1176
 * Deprecated: 2.56: Use g_data_input_stream_read_upto_async() instead, which
 *     has more consistent behaviour regarding the stop character.
Matthias Clasen's avatar
Matthias Clasen committed
1177
 */
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
void
g_data_input_stream_read_until_async (GDataInputStream    *stream,
                                      const gchar         *stop_chars,
                                      gint                 io_priority,
                                      GCancellable        *cancellable,
                                      GAsyncReadyCallback  callback,
                                      gpointer             user_data)
{
  g_return_if_fail (G_IS_DATA_INPUT_STREAM (stream));
  g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
  g_return_if_fail (stop_chars != NULL);

1190
  g_data_input_stream_read_async (stream, stop_chars, -1, io_priority,
1191
                                  cancellable, callback, user_data);
1192 1193 1194 1195 1196 1197
}

/**
 * g_data_input_stream_read_line_finish:
 * @stream: a given #GDataInputStream.
 * @result: the #GAsyncResult that was provided to the callback.
1198
 * @length: (out) (optional): a #gsize to get the length of the data read in.
1199 1200 1201
 * @error: #GError for error reporting.
 *
 * Finish an asynchronous call started by
1202 1203 1204
 * g_data_input_stream_read_line_async().  Note the warning about
 * string encoding in g_data_input_stream_read_line() applies here as
 * well.
Matthias Clasen's avatar
Matthias Clasen committed
1205
 *
1206 1207 1208 1209 1210 1211
 * Returns: (nullable) (transfer full) (array zero-terminated=1) (element-type guint8):
 *  a NUL-terminated byte array with the line that was read in
 *  (without the newlines).  Set @length to a #gsize to get the length
 *  of the read line.  On an error, it will return %NULL and @error
 *  will be set. If there's no content to read, it will still return
 *  %NULL, but @error won't be set.
Matthias Clasen's avatar
Matthias Clasen committed
1212
 *
1213
 * Since: 2.20
Matthias Clasen's avatar
Matthias Clasen committed
1214
 */
1215 1216 1217 1218 1219 1220
gchar *
g_data_input_stream_read_line_finish (GDataInputStream  *stream,
                                      GAsyncResult      *result,
                                      gsize             *length,
                                      GError           **error)
{
1221
  g_return_val_if_fail (g_task_is_valid (result, stream), NULL);
1222 1223 1224 1225

  return g_data_input_stream_read_finish (stream, result, length, error);
}

1226 1227 1228 1229
/**
 * g_data_input_stream_read_line_finish_utf8:
 * @stream: a given #GDataInputStream.
 * @result: the #GAsyncResult that was provided to the callback.
1230
 * @length: (out) (optional): a #gsize to get the length of the data read in.
1231 1232 1233 1234 1235
 * @error: #GError for error reporting.
 *
 * Finish an asynchronous call started by
 * g_data_input_stream_read_line_async().
 *
1236 1237 1238 1239 1240 1241
 * Returns: (nullable) (transfer full): a string with the line that
 *  was read in (without the newlines).  Set @length to a #gsize to
 *  get the length of the read line.  On an error, it will return
 *  %NULL and @error will be set. For UTF-8 conversion errors, the set
 *  error domain is %G_CONVERT_ERROR.  If there's no content to read,
 *  it will still return %NULL, but @error won't be set.
1242
 *
1243
 * Since: 2.30
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
 */
gchar *
g_data_input_stream_read_line_finish_utf8 (GDataInputStream  *stream,
					   GAsyncResult      *result,
					   gsize             *length,
					   GError           **error)
{
  gchar *res;

  res = g_data_input_stream_read_line_finish (stream, result, length, error);
1254 1255 1256
  if (!res)
    return NULL;

1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
  if (!g_utf8_validate (res, -1, NULL))
    {
      g_set_error_literal (error, G_CONVERT_ERROR,
			   G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
			   _("Invalid byte sequence in conversion input"));
      g_free (res);
      return NULL;
    }
  return res;
}

1268 1269 1270 1271
/**
 * g_data_input_stream_read_until_finish:
 * @stream: a given #GDataInputStream.
 * @result: the #GAsyncResult that was provided to the callback.
1272
 * @length: (out) (optional): a #gsize to get the length of the data read in.
1273 1274 1275 1276
 * @error: #GError for error reporting.
 *
 * Finish an asynchronous call started by
 * g_data_input_stream_read_until_async().
Matthias Clasen's avatar
Matthias Clasen committed
1277 1278
 *
 * Since: 2.20
Matthias Clasen's avatar
Matthias Clasen committed
1279
 *
1280 1281 1282 1283
 * Returns: (transfer full): a string with the data that was read
 *     before encountering any of the stop characters. Set @length to
 *     a #gsize to get the length of the string. This function will
 *     return %NULL on an error.
1284 1285
 * Deprecated: 2.56: Use g_data_input_stream_read_upto_finish() instead, which
 *     has more consistent behaviour regarding the stop character.
Matthias Clasen's avatar
Matthias Clasen committed
1286
 */
1287 1288 1289 1290 1291 1292
gchar *
g_data_input_stream_read_until_finish (GDataInputStream  *stream,
                                       GAsyncResult      *result,
                                       gsize             *length,
                                       GError           **error)
{
1293
  g_return_val_if_fail (g_task_is_valid (result, stream), NULL);
1294 1295 1296

  return g_data_input_stream_read_finish (stream, result, length, error);
}
1297 1298 1299 1300

/**
 * g_data_input_stream_read_upto:
 * @stream: a #GDataInputStream
1301
 * @stop_chars: characters to terminate the read
1302 1303
 * @stop_chars_len: length of @stop_chars. May be -1 if @stop_chars is
 *     nul-terminated
1304
 * @length: (out) (optional): a #gsize to get the length of the data read in
1305
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore
1306 1307 1308 1309 1310 1311
 * @error: #GError for error reporting
 *
 * Reads a string from the data input stream, up to the first
 * occurrence of any of the stop characters.
 *
 * In contrast to g_data_input_stream_read_until(), this function
1312 1313
 * does not consume the stop character. You have to use
 * g_data_input_stream_read_byte() to get it before calling
1314 1315 1316 1317 1318
 * g_data_input_stream_read_upto() again.
 *
 * Note that @stop_chars may contain '\0' if @stop_chars_len is
 * specified.
 *
1319 1320
 * The returned string will always be nul-terminated on success.
 *
1321 1322 1323 1324
 * Returns: (transfer full): a string with the data that was read
 *     before encountering any of the stop characters. Set @length to
 *     a #gsize to get the length of the string. This function will
 *     return %NULL on an error
1325
 *
1326
 * Since: 2.26
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
 */
char *
g_data_input_stream_read_upto (GDataInputStream  *stream,
                               const gchar       *stop_chars,
                               gssize             stop_chars_len,
                               gsize             *length,
                               GCancellable      *cancellable,
                               GError           **error)
{
  GBufferedInputStream *bstream;
  gsize checked;
  gssize found_pos;
  gssize res;
  char *data_until;

  g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), NULL);

  if (stop_chars_len < 0)
    stop_chars_len = strlen (stop_chars);

  bstream = G_BUFFERED_INPUT_STREAM (stream);

  checked = 0;

  while ((found_pos = scan_for_chars (stream, &checked, stop_chars, stop_chars_len)) == -1)
    {
      if (g_buffered_input_stream_get_available (bstream) ==
          g_buffered_input_stream_get_buffer_size (bstream))
        g_buffered_input_stream_set_buffer_size (bstream,
                                                 2 * g_buffered_input_stream_get_buffer_size (bstream));

      res = g_buffered_input_stream_fill (bstream, -1, cancellable, error);
      if (res < 0)
        return NULL;
      if (res == 0)
        {
          /* End of stream */
          if (g_buffered_input_stream_get_available (bstream) == 0)
            {
              if (length)
                *length = 0;
              return NULL;
            }
          else
            {
              found_pos = checked;
              break;
            }
        }
    }

  data_until = g_malloc (found_pos + 1);

  res = g_input_stream_read (G_INPUT_STREAM (stream),
                             data_until,
                             found_pos,
                             NULL, NULL);
  if (length)
    *length = (gsize)found_pos;
  g_warn_if_fail (res == found_pos);
  data_until[found_pos] = 0;

  return data_until;
}

/**
 * g_data_input_stream_read_upto_async:
 * @stream: a #GDataInputStream
1395
 * @stop_chars: characters to terminate the read
1396 1397
 * @stop_chars_len: length of @stop_chars. May be -1 if @stop_chars is
 *     nul-terminated
1398
 * @io_priority: the [I/O priority][io-priority] of the request
1399
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore
1400 1401
 * @callback: (scope async): callback to call when the request is satisfied
 * @user_data: (closure): the data to pass to callback function
1402 1403 1404 1405 1406
 *
 * The asynchronous version of g_data_input_stream_read_upto().
 * It is an error to have two outstanding calls to this function.
 *
 * In contrast to g_data_input_stream_read_until(), this function
1407 1408
 * does not consume the stop character. You have to use
 * g_data_input_stream_read_byte() to get it before calling
1409 1410 1411 1412 1413 1414 1415 1416 1417
 * g_data_input_stream_read_upto() again.
 *
 * Note that @stop_chars may contain '\0' if @stop_chars_len is
 * specified.
 *
 * When the operation is finished, @callback will be called. You
 * can then call g_data_input_stream_read_upto_finish() to get
 * the result of the operation.
 *
1418
 * Since: 2.26
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
 */
void
g_data_input_stream_read_upto_async (GDataInputStream    *stream,
                                     const gchar         *stop_chars,
                                     gssize               stop_chars_len,
                                     gint                 io_priority,
                                     GCancellable        *cancellable,
                                     GAsyncReadyCallback  callback,
                                     gpointer             user_data)
{
  g_return_if_fail (G_IS_DATA_INPUT_STREAM (stream));
  g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
  g_return_if_fail (stop_chars != NULL);

  g_data_input_stream_read_async (stream, stop_chars, stop_chars_len, io_priority,
1434
                                  cancellable, callback, user_data);
1435 1436 1437 1438 1439 1440
}

/**
 * g_data_input_stream_read_upto_finish:
 * @stream: a #GDataInputStream
 * @result: the #GAsyncResult that was provided to the callback
1441
 * @length: (out) (optional): a #gsize to get the length of the data read in
1442 1443 1444 1445 1446
 * @error: #GError for error reporting
 *
 * Finish an asynchronous call started by
 * g_data_input_stream_read_upto_async().
 *
1447 1448 1449
 * Note that this function does not consume the stop character. You
 * have to use g_data_input_stream_read_byte() to get it before calling
 * g_data_input_stream_read_upto_async() again.
1450
 *
1451 1452
 * The returned string will always be nul-terminated on success.
 *
1453 1454 1455 1456
 * Returns: (transfer full): a string with the data that was read
 *     before encountering any of the stop characters. Set @length to
 *     a #gsize to get the length of the string. This function will
 *     return %NULL on an error.
1457 1458 1459 1460 1461 1462 1463 1464 1465
 *
 * Since: 2.24
 */
gchar *
g_data_input_stream_read_upto_finish (GDataInputStream  *stream,
                                      GAsyncResult      *result,
                                      gsize             *length,
                                      GError           **error)
{
1466
  g_return_val_if_fail (g_task_is_valid (result, stream), NULL);
1467 1468 1469

  return g_data_input_stream_read_finish (stream, result, length, error);
}