Coverage Report

Created: 2025-07-01 07:09

/src/glib/gio/gmemoryoutputstream.c
Line
Count
Source (jump to first uncovered line)
1
/* GIO - GLib Input, Output and Streaming Library
2
 * 
3
 * Copyright (C) 2006-2007 Red Hat, Inc.
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2.1 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General
16
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
17
 *
18
 * Authors:
19
 *   Christian Kellner <gicmo@gnome.org>
20
 *   Krzysztof KosiƄski <tweenk.pl@gmail.com>
21
 */
22
23
#include "config.h"
24
#include "gmemoryoutputstream.h"
25
#include "goutputstream.h"
26
#include "gpollableoutputstream.h"
27
#include "gseekable.h"
28
#include "gtask.h"
29
#include "gioerror.h"
30
#include "string.h"
31
#include "glibintl.h"
32
33
34
/**
35
 * SECTION:gmemoryoutputstream
36
 * @short_description: Streaming output operations on memory chunks
37
 * @include: gio/gio.h
38
 * @see_also: #GMemoryInputStream
39
 *
40
 * #GMemoryOutputStream is a class for using arbitrary
41
 * memory chunks as output for GIO streaming output operations.
42
 *
43
 * As of GLib 2.34, #GMemoryOutputStream trivially implements
44
 * #GPollableOutputStream: it always polls as ready.
45
 */
46
47
#define MIN_ARRAY_SIZE  16
48
49
enum {
50
  PROP_0,
51
  PROP_DATA,
52
  PROP_SIZE,
53
  PROP_DATA_SIZE,
54
  PROP_REALLOC_FUNCTION,
55
  PROP_DESTROY_FUNCTION
56
};
57
58
struct _GMemoryOutputStreamPrivate
59
{
60
  gpointer       data; /* Write buffer */
61
  gsize          len; /* Current length of the data buffer. Can change with resizing. */
62
  gsize          valid_len; /* The part of data that has been written to */
63
  gsize          pos; /* Current position in the stream. Distinct from valid_len,
64
                         because the stream is seekable. */
65
66
  GReallocFunc   realloc_fn;
67
  GDestroyNotify destroy;
68
};
69
70
static void     g_memory_output_stream_set_property (GObject      *object,
71
                                                     guint         prop_id,
72
                                                     const GValue *value,
73
                                                     GParamSpec   *pspec);
74
static void     g_memory_output_stream_get_property (GObject      *object,
75
                                                     guint         prop_id,
76
                                                     GValue       *value,
77
                                                     GParamSpec   *pspec);
78
static void     g_memory_output_stream_finalize     (GObject      *object);
79
80
static gssize   g_memory_output_stream_write       (GOutputStream *stream,
81
                                                    const void    *buffer,
82
                                                    gsize          count,
83
                                                    GCancellable  *cancellable,
84
                                                    GError       **error);
85
86
static gboolean g_memory_output_stream_close       (GOutputStream  *stream,
87
                                                    GCancellable   *cancellable,
88
                                                    GError        **error);
89
90
static void     g_memory_output_stream_close_async  (GOutputStream        *stream,
91
                                                     int                   io_priority,
92
                                                     GCancellable         *cancellable,
93
                                                     GAsyncReadyCallback   callback,
94
                                                     gpointer              data);
95
static gboolean g_memory_output_stream_close_finish (GOutputStream        *stream,
96
                                                     GAsyncResult         *result,
97
                                                     GError              **error);
98
99
static void     g_memory_output_stream_seekable_iface_init (GSeekableIface  *iface);
100
static goffset  g_memory_output_stream_tell                (GSeekable       *seekable);
101
static gboolean g_memory_output_stream_can_seek            (GSeekable       *seekable);
102
static gboolean g_memory_output_stream_seek                (GSeekable       *seekable,
103
                                                           goffset          offset,
104
                                                           GSeekType        type,
105
                                                           GCancellable    *cancellable,
106
                                                           GError         **error);
107
static gboolean g_memory_output_stream_can_truncate        (GSeekable       *seekable);
108
static gboolean g_memory_output_stream_truncate            (GSeekable       *seekable,
109
                                                           goffset          offset,
110
                                                           GCancellable    *cancellable,
111
                                                           GError         **error);
112
113
static gboolean g_memory_output_stream_is_writable       (GPollableOutputStream *stream);
114
static GSource *g_memory_output_stream_create_source     (GPollableOutputStream *stream,
115
                                                          GCancellable          *cancellable);
116
117
static void g_memory_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface);
118
119
G_DEFINE_TYPE_WITH_CODE (GMemoryOutputStream, g_memory_output_stream, G_TYPE_OUTPUT_STREAM,
120
                         G_ADD_PRIVATE (GMemoryOutputStream)
121
                         G_IMPLEMENT_INTERFACE (G_TYPE_SEEKABLE,
122
                                                g_memory_output_stream_seekable_iface_init);
123
                         G_IMPLEMENT_INTERFACE (G_TYPE_POLLABLE_OUTPUT_STREAM,
124
                                                g_memory_output_stream_pollable_iface_init))
125
126
127
static void
128
g_memory_output_stream_class_init (GMemoryOutputStreamClass *klass)
129
0
{
130
0
  GOutputStreamClass *ostream_class;
131
0
  GObjectClass *gobject_class;
132
133
0
  gobject_class = G_OBJECT_CLASS (klass);
134
0
  gobject_class->set_property = g_memory_output_stream_set_property;
135
0
  gobject_class->get_property = g_memory_output_stream_get_property;
136
0
  gobject_class->finalize     = g_memory_output_stream_finalize;
137
138
0
  ostream_class = G_OUTPUT_STREAM_CLASS (klass);
139
140
0
  ostream_class->write_fn = g_memory_output_stream_write;
141
0
  ostream_class->close_fn = g_memory_output_stream_close;
142
0
  ostream_class->close_async  = g_memory_output_stream_close_async;
143
0
  ostream_class->close_finish = g_memory_output_stream_close_finish;
144
145
  /**
146
   * GMemoryOutputStream:data:
147
   *
148
   * Pointer to buffer where data will be written.
149
   *
150
   * Since: 2.24
151
   **/
152
0
  g_object_class_install_property (gobject_class,
153
0
                                   PROP_DATA,
154
0
                                   g_param_spec_pointer ("data",
155
0
                                                         P_("Data Buffer"),
156
0
                                                         P_("Pointer to buffer where data will be written."),
157
0
                                                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
158
0
                                                         G_PARAM_STATIC_STRINGS));
159
160
  /**
161
   * GMemoryOutputStream:size:
162
   *
163
   * Current size of the data buffer.
164
   *
165
   * Since: 2.24
166
   **/
167
0
  g_object_class_install_property (gobject_class,
168
0
                                   PROP_SIZE,
169
0
                                   g_param_spec_ulong ("size",
170
0
                                                       P_("Data Buffer Size"),
171
0
                                                       P_("Current size of the data buffer."),
172
0
                                                       0, G_MAXULONG, 0,
173
0
                                                       G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
174
0
                                                       G_PARAM_STATIC_STRINGS));
175
176
  /**
177
   * GMemoryOutputStream:data-size:
178
   *
179
   * Size of data written to the buffer.
180
   *
181
   * Since: 2.24
182
   **/
183
0
  g_object_class_install_property (gobject_class,
184
0
                                   PROP_DATA_SIZE,
185
0
                                   g_param_spec_ulong ("data-size",
186
0
                                                       P_("Data Size"),
187
0
                                                       P_("Size of data written to the buffer."),
188
0
                                                       0, G_MAXULONG, 0,
189
0
                                                       G_PARAM_READABLE |
190
0
                                                       G_PARAM_STATIC_STRINGS));
191
192
  /**
193
   * GMemoryOutputStream:realloc-function: (skip)
194
   *
195
   * Function with realloc semantics called to enlarge the buffer.
196
   *
197
   * Since: 2.24
198
   **/
199
0
  g_object_class_install_property (gobject_class,
200
0
                                   PROP_REALLOC_FUNCTION,
201
0
                                   g_param_spec_pointer ("realloc-function",
202
0
                                                         P_("Memory Reallocation Function"),
203
0
                                                         P_("Function with realloc semantics called to enlarge the buffer."),
204
0
                                                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
205
0
                                                         G_PARAM_STATIC_STRINGS));
206
207
  /**
208
   * GMemoryOutputStream:destroy-function: (skip)
209
   *
210
   * Function called with the buffer as argument when the stream is destroyed.
211
   *
212
   * Since: 2.24
213
   **/
214
0
  g_object_class_install_property (gobject_class,
215
0
                                   PROP_DESTROY_FUNCTION,
216
0
                                   g_param_spec_pointer ("destroy-function",
217
0
                                                         P_("Destroy Notification Function"),
218
0
                                                         P_("Function called with the buffer as argument when the stream is destroyed."),
219
0
                                                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
220
0
                                                         G_PARAM_STATIC_STRINGS));
221
0
}
222
223
static void
224
g_memory_output_stream_pollable_iface_init (GPollableOutputStreamInterface *iface)
225
0
{
226
0
  iface->is_writable = g_memory_output_stream_is_writable;
227
0
  iface->create_source = g_memory_output_stream_create_source;
228
0
}
229
230
static void
231
g_memory_output_stream_set_property (GObject      *object,
232
                                     guint         prop_id,
233
                                     const GValue *value,
234
                                     GParamSpec   *pspec)
235
0
{
236
0
  GMemoryOutputStream        *stream;
237
0
  GMemoryOutputStreamPrivate *priv;
238
239
0
  stream = G_MEMORY_OUTPUT_STREAM (object);
240
0
  priv = stream->priv;
241
242
0
  switch (prop_id)
243
0
    {
244
0
    case PROP_DATA:
245
0
      priv->data = g_value_get_pointer (value);
246
0
      break;
247
0
    case PROP_SIZE:
248
0
      priv->len = g_value_get_ulong (value);
249
0
      break;
250
0
    case PROP_REALLOC_FUNCTION:
251
0
      priv->realloc_fn = g_value_get_pointer (value);
252
0
      break;
253
0
    case PROP_DESTROY_FUNCTION:
254
0
      priv->destroy = g_value_get_pointer (value);
255
0
      break;
256
0
    default:
257
0
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
258
0
      break;
259
0
    }
260
0
}
261
262
static void
263
g_memory_output_stream_get_property (GObject      *object,
264
                                     guint         prop_id,
265
                                     GValue       *value,
266
                                     GParamSpec   *pspec)
267
0
{
268
0
  GMemoryOutputStream        *stream;
269
0
  GMemoryOutputStreamPrivate *priv;
270
271
0
  stream = G_MEMORY_OUTPUT_STREAM (object);
272
0
  priv = stream->priv;
273
274
0
  switch (prop_id)
275
0
    {
276
0
    case PROP_DATA:
277
0
      g_value_set_pointer (value, priv->data);
278
0
      break;
279
0
    case PROP_SIZE:
280
0
      g_value_set_ulong (value, priv->len);
281
0
      break;
282
0
    case PROP_DATA_SIZE:
283
0
      g_value_set_ulong (value, priv->valid_len);
284
0
      break;
285
0
    case PROP_REALLOC_FUNCTION:
286
0
      g_value_set_pointer (value, priv->realloc_fn);
287
0
      break;
288
0
    case PROP_DESTROY_FUNCTION:
289
0
      g_value_set_pointer (value, priv->destroy);
290
0
      break;
291
0
    default:
292
0
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
293
0
      break;
294
0
    }
295
0
}
296
297
static void
298
g_memory_output_stream_finalize (GObject *object)
299
0
{
300
0
  GMemoryOutputStream        *stream;
301
0
  GMemoryOutputStreamPrivate *priv;
302
303
0
  stream = G_MEMORY_OUTPUT_STREAM (object);
304
0
  priv = stream->priv;
305
  
306
0
  if (priv->destroy)
307
0
    priv->destroy (priv->data);
308
309
0
  G_OBJECT_CLASS (g_memory_output_stream_parent_class)->finalize (object);
310
0
}
311
312
static void
313
g_memory_output_stream_seekable_iface_init (GSeekableIface *iface)
314
0
{
315
0
  iface->tell         = g_memory_output_stream_tell;
316
0
  iface->can_seek     = g_memory_output_stream_can_seek;
317
0
  iface->seek         = g_memory_output_stream_seek;
318
0
  iface->can_truncate = g_memory_output_stream_can_truncate;
319
0
  iface->truncate_fn  = g_memory_output_stream_truncate;
320
0
}
321
322
323
static void
324
g_memory_output_stream_init (GMemoryOutputStream *stream)
325
0
{
326
0
  stream->priv = g_memory_output_stream_get_instance_private (stream);
327
0
  stream->priv->pos = 0;
328
0
  stream->priv->valid_len = 0;
329
0
}
330
331
/**
332
 * g_memory_output_stream_new: (skip)
333
 * @data: (nullable): pointer to a chunk of memory to use, or %NULL
334
 * @size: the size of @data
335
 * @realloc_function: (nullable): a function with realloc() semantics (like g_realloc())
336
 *     to be called when @data needs to be grown, or %NULL
337
 * @destroy_function: (nullable): a function to be called on @data when the stream is
338
 *     finalized, or %NULL
339
 *
340
 * Creates a new #GMemoryOutputStream.
341
 *
342
 * In most cases this is not the function you want.  See
343
 * g_memory_output_stream_new_resizable() instead.
344
 *
345
 * If @data is non-%NULL, the stream will use that for its internal storage.
346
 *
347
 * If @realloc_fn is non-%NULL, it will be used for resizing the internal
348
 * storage when necessary and the stream will be considered resizable.
349
 * In that case, the stream will start out being (conceptually) empty.
350
 * @size is used only as a hint for how big @data is.  Specifically,
351
 * seeking to the end of a newly-created stream will seek to zero, not
352
 * @size.  Seeking past the end of the stream and then writing will
353
 * introduce a zero-filled gap.
354
 *
355
 * If @realloc_fn is %NULL then the stream is fixed-sized.  Seeking to
356
 * the end will seek to @size exactly.  Writing past the end will give
357
 * an 'out of space' error.  Attempting to seek past the end will fail.
358
 * Unlike the resizable case, seeking to an offset within the stream and
359
 * writing will preserve the bytes passed in as @data before that point
360
 * and will return them as part of g_memory_output_stream_steal_data().
361
 * If you intend to seek you should probably therefore ensure that @data
362
 * is properly initialised.
363
 *
364
 * It is probably only meaningful to provide @data and @size in the case
365
 * that you want a fixed-sized stream.  Put another way: if @realloc_fn
366
 * is non-%NULL then it makes most sense to give @data as %NULL and
367
 * @size as 0 (allowing #GMemoryOutputStream to do the initial
368
 * allocation for itself).
369
 *
370
 * |[<!-- language="C" -->
371
 * // a stream that can grow
372
 * stream = g_memory_output_stream_new (NULL, 0, realloc, free);
373
 *
374
 * // another stream that can grow
375
 * stream2 = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
376
 *
377
 * // a fixed-size stream
378
 * data = malloc (200);
379
 * stream3 = g_memory_output_stream_new (data, 200, NULL, free);
380
 * ]|
381
 *
382
 * Returns: A newly created #GMemoryOutputStream object.
383
 **/
384
GOutputStream *
385
g_memory_output_stream_new (gpointer       data,
386
                            gsize          size,
387
                            GReallocFunc   realloc_function,
388
                            GDestroyNotify destroy_function)
389
0
{
390
0
  GOutputStream *stream;
391
392
0
  stream = g_object_new (G_TYPE_MEMORY_OUTPUT_STREAM,
393
0
                         "data", data,
394
0
                         "size", size,
395
0
                         "realloc-function", realloc_function,
396
0
                         "destroy-function", destroy_function,
397
0
                         NULL);
398
399
0
  return stream;
400
0
}
401
402
/**
403
 * g_memory_output_stream_new_resizable:
404
 *
405
 * Creates a new #GMemoryOutputStream, using g_realloc() and g_free()
406
 * for memory allocation.
407
 *
408
 * Since: 2.36
409
 */
410
GOutputStream *
411
g_memory_output_stream_new_resizable (void)
412
0
{
413
0
  return g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
414
0
}
415
416
/**
417
 * g_memory_output_stream_get_data:
418
 * @ostream: a #GMemoryOutputStream
419
 *
420
 * Gets any loaded data from the @ostream.
421
 *
422
 * Note that the returned pointer may become invalid on the next
423
 * write or truncate operation on the stream.
424
 *
425
 * Returns: (transfer none): pointer to the stream's data, or %NULL if the data
426
 *    has been stolen
427
 **/
428
gpointer
429
g_memory_output_stream_get_data (GMemoryOutputStream *ostream)
430
0
{
431
0
  g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
432
433
0
  return ostream->priv->data;
434
0
}
435
436
/**
437
 * g_memory_output_stream_get_size:
438
 * @ostream: a #GMemoryOutputStream
439
 *
440
 * Gets the size of the currently allocated data area (available from
441
 * g_memory_output_stream_get_data()).
442
 *
443
 * You probably don't want to use this function on resizable streams.
444
 * See g_memory_output_stream_get_data_size() instead.  For resizable
445
 * streams the size returned by this function is an implementation
446
 * detail and may be change at any time in response to operations on the
447
 * stream.
448
 *
449
 * If the stream is fixed-sized (ie: no realloc was passed to
450
 * g_memory_output_stream_new()) then this is the maximum size of the
451
 * stream and further writes will return %G_IO_ERROR_NO_SPACE.
452
 *
453
 * In any case, if you want the number of bytes currently written to the
454
 * stream, use g_memory_output_stream_get_data_size().
455
 *
456
 * Returns: the number of bytes allocated for the data buffer
457
 */
458
gsize
459
g_memory_output_stream_get_size (GMemoryOutputStream *ostream)
460
0
{
461
0
  g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
462
463
0
  return ostream->priv->len;
464
0
}
465
466
/**
467
 * g_memory_output_stream_get_data_size:
468
 * @ostream: a #GMemoryOutputStream
469
 *
470
 * Returns the number of bytes from the start up to including the last
471
 * byte written in the stream that has not been truncated away.
472
 *
473
 * Returns: the number of bytes written to the stream
474
 *
475
 * Since: 2.18
476
 */
477
gsize
478
g_memory_output_stream_get_data_size (GMemoryOutputStream *ostream)
479
0
{
480
0
  g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
481
482
0
  return ostream->priv->valid_len;
483
0
}
484
485
/**
486
 * g_memory_output_stream_steal_data:
487
 * @ostream: a #GMemoryOutputStream
488
 *
489
 * Gets any loaded data from the @ostream. Ownership of the data
490
 * is transferred to the caller; when no longer needed it must be
491
 * freed using the free function set in @ostream's
492
 * #GMemoryOutputStream:destroy-function property.
493
 *
494
 * @ostream must be closed before calling this function.
495
 *
496
 * Returns: (transfer full): the stream's data, or %NULL if it has previously
497
 *    been stolen
498
 *
499
 * Since: 2.26
500
 **/
501
gpointer
502
g_memory_output_stream_steal_data (GMemoryOutputStream *ostream)
503
0
{
504
0
  gpointer data;
505
506
0
  g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
507
0
  g_return_val_if_fail (g_output_stream_is_closed (G_OUTPUT_STREAM (ostream)), NULL);
508
509
0
  data = ostream->priv->data;
510
0
  ostream->priv->data = NULL;
511
512
0
  return data;
513
0
}
514
515
/**
516
 * g_memory_output_stream_steal_as_bytes:
517
 * @ostream: a #GMemoryOutputStream
518
 *
519
 * Returns data from the @ostream as a #GBytes. @ostream must be
520
 * closed before calling this function.
521
 *
522
 * Returns: (transfer full): the stream's data
523
 *
524
 * Since: 2.34
525
 **/
526
GBytes *
527
g_memory_output_stream_steal_as_bytes (GMemoryOutputStream *ostream)
528
0
{
529
0
  GBytes *result;
530
531
0
  g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
532
0
  g_return_val_if_fail (g_output_stream_is_closed (G_OUTPUT_STREAM (ostream)), NULL);
533
534
0
  result = g_bytes_new_with_free_func (ostream->priv->data,
535
0
                                       ostream->priv->valid_len,
536
0
                                       ostream->priv->destroy,
537
0
                                       ostream->priv->data);
538
0
  ostream->priv->data = NULL;
539
540
0
  return result;
541
0
}
542
543
static gboolean
544
array_resize (GMemoryOutputStream  *ostream,
545
              gsize                 size,
546
              gboolean              allow_partial,
547
              GError              **error)
548
0
{
549
0
  GMemoryOutputStreamPrivate *priv;
550
0
  gpointer data;
551
0
  gsize len;
552
553
0
  priv = ostream->priv;
554
555
0
  if (priv->len == size)
556
0
    return TRUE;
557
558
0
  if (!priv->realloc_fn)
559
0
    {
560
0
      if (allow_partial &&
561
0
          priv->pos < priv->len)
562
0
        return TRUE; /* Short write */
563
564
0
      g_set_error_literal (error,
565
0
                           G_IO_ERROR,
566
0
                           G_IO_ERROR_NO_SPACE,
567
0
                           _("Memory output stream not resizable"));
568
0
      return FALSE;
569
0
    }
570
571
0
  len = priv->len;
572
0
  data = priv->realloc_fn (priv->data, size);
573
574
0
  if (size > 0 && !data)
575
0
    {
576
0
      if (allow_partial &&
577
0
          priv->pos < priv->len)
578
0
        return TRUE; /* Short write */
579
580
0
      g_set_error_literal (error,
581
0
                           G_IO_ERROR,
582
0
                           G_IO_ERROR_NO_SPACE,
583
0
                           _("Failed to resize memory output stream"));
584
0
      return FALSE;
585
0
    }
586
587
0
  if (size > len)
588
0
    memset ((guint8 *)data + len, 0, size - len);
589
590
0
  priv->data = data;
591
0
  priv->len = size;
592
593
0
  if (priv->len < priv->valid_len)
594
0
    priv->valid_len = priv->len;
595
596
0
  return TRUE;
597
0
}
598
599
static gsize
600
g_nearest_pow (gsize num)
601
0
{
602
0
  gsize n = 1;
603
604
0
  while (n < num && n > 0)
605
0
    n <<= 1;
606
607
0
  return n;
608
0
}
609
610
static gssize
611
g_memory_output_stream_write (GOutputStream  *stream,
612
                              const void     *buffer,
613
                              gsize           count,
614
                              GCancellable   *cancellable,
615
                              GError        **error)
616
0
{
617
0
  GMemoryOutputStream        *ostream;
618
0
  GMemoryOutputStreamPrivate *priv;
619
0
  guint8   *dest;
620
0
  gsize new_size;
621
622
0
  ostream = G_MEMORY_OUTPUT_STREAM (stream);
623
0
  priv = ostream->priv;
624
625
0
  if (count == 0)
626
0
    return 0;
627
628
  /* Check for address space overflow, but only if the buffer is resizable.
629
     Otherwise we just do a short write and don't worry. */
630
0
  if (priv->realloc_fn && priv->pos + count < priv->pos)
631
0
    goto overflow;
632
633
0
  if (priv->pos + count > priv->len)
634
0
    {
635
      /* At least enough to fit the write, rounded up for greater than
636
       * linear growth.
637
       *
638
       * Assuming that we're using something like realloc(), the kernel
639
       * will overcommit memory to us, so doubling the size each time
640
       * will keep the number of realloc calls low without wasting too
641
       * much memory.
642
       */
643
0
      new_size = g_nearest_pow (priv->pos + count);
644
      /* Check for overflow again. We have checked if
645
         pos + count > G_MAXSIZE, but now check if g_nearest_pow () has
646
         overflowed */
647
0
      if (new_size == 0)
648
0
        goto overflow;
649
650
0
      new_size = MAX (new_size, MIN_ARRAY_SIZE);
651
0
      if (!array_resize (ostream, new_size, TRUE, error))
652
0
        return -1;
653
0
    }
654
655
  /* Make sure we handle short writes if the array_resize
656
     only added part of the required memory */
657
0
  count = MIN (count, priv->len - priv->pos);
658
659
0
  dest = (guint8 *)priv->data + priv->pos;
660
0
  memcpy (dest, buffer, count);
661
0
  priv->pos += count;
662
663
0
  if (priv->pos > priv->valid_len)
664
0
    priv->valid_len = priv->pos;
665
666
0
  return count;
667
668
0
 overflow:
669
  /* Overflow: buffer size would need to be bigger than G_MAXSIZE. */
670
0
  g_set_error_literal (error,
671
0
                       G_IO_ERROR,
672
0
                       G_IO_ERROR_NO_SPACE,
673
0
                       _("Amount of memory required to process the write is "
674
0
                         "larger than available address space"));
675
0
  return -1;
676
0
}
677
678
static gboolean
679
g_memory_output_stream_close (GOutputStream  *stream,
680
                              GCancellable   *cancellable,
681
                              GError        **error)
682
0
{
683
0
  return TRUE;
684
0
}
685
686
static void
687
g_memory_output_stream_close_async (GOutputStream       *stream,
688
                                    int                  io_priority,
689
                                    GCancellable        *cancellable,
690
                                    GAsyncReadyCallback  callback,
691
                                    gpointer             data)
692
0
{
693
0
  GTask *task;
694
695
0
  task = g_task_new (stream, cancellable, callback, data);
696
0
  g_task_set_source_tag (task, g_memory_output_stream_close_async);
697
698
  /* will always return TRUE */
699
0
  g_memory_output_stream_close (stream, cancellable, NULL);
700
701
0
  g_task_return_boolean (task, TRUE);
702
0
  g_object_unref (task);
703
0
}
704
705
static gboolean
706
g_memory_output_stream_close_finish (GOutputStream  *stream,
707
                                     GAsyncResult   *result,
708
                                     GError        **error)
709
0
{
710
0
  g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
711
712
0
  return g_task_propagate_boolean (G_TASK (result), error);
713
0
}
714
715
static goffset
716
g_memory_output_stream_tell (GSeekable *seekable)
717
0
{
718
0
  GMemoryOutputStream *stream;
719
0
  GMemoryOutputStreamPrivate *priv;
720
721
0
  stream = G_MEMORY_OUTPUT_STREAM (seekable);
722
0
  priv = stream->priv;
723
724
0
  return priv->pos;
725
0
}
726
727
static gboolean
728
g_memory_output_stream_can_seek (GSeekable *seekable)
729
0
{
730
0
  return TRUE;
731
0
}
732
733
static gboolean
734
g_memory_output_stream_seek (GSeekable    *seekable,
735
                             goffset        offset,
736
                             GSeekType      type,
737
                             GCancellable  *cancellable,
738
                             GError       **error)
739
0
{
740
0
  GMemoryOutputStream        *stream;
741
0
  GMemoryOutputStreamPrivate *priv;
742
0
  goffset absolute;
743
744
0
  stream = G_MEMORY_OUTPUT_STREAM (seekable);
745
0
  priv = stream->priv;
746
747
0
  switch (type)
748
0
    {
749
0
    case G_SEEK_CUR:
750
0
      absolute = priv->pos + offset;
751
0
      break;
752
753
0
    case G_SEEK_SET:
754
0
      absolute = offset;
755
0
      break;
756
757
0
    case G_SEEK_END:
758
      /* For resizable streams, we consider the end to be the data
759
       * length.  For fixed-sized streams, we consider the end to be the
760
       * size of the buffer.
761
       */
762
0
      if (priv->realloc_fn)
763
0
        absolute = priv->valid_len + offset;
764
0
      else
765
0
        absolute = priv->len + offset;
766
0
      break;
767
768
0
    default:
769
0
      g_set_error_literal (error,
770
0
                           G_IO_ERROR,
771
0
                           G_IO_ERROR_INVALID_ARGUMENT,
772
0
                           _("Invalid GSeekType supplied"));
773
774
0
      return FALSE;
775
0
    }
776
777
0
  if (absolute < 0)
778
0
    {
779
0
      g_set_error_literal (error,
780
0
                           G_IO_ERROR,
781
0
                           G_IO_ERROR_INVALID_ARGUMENT,
782
0
                           _("Requested seek before the beginning of the stream"));
783
0
      return FALSE;
784
0
    }
785
786
  /* Can't seek past the end of a fixed-size stream.
787
   *
788
   * Note: seeking to the non-existent byte at the end of a fixed-sized
789
   * stream is valid (eg: a 1-byte fixed sized stream can have position
790
   * 0 or 1).  Therefore '>' is what we want.
791
   * */
792
0
  if (priv->realloc_fn == NULL && (gsize) absolute > priv->len)
793
0
    {
794
0
      g_set_error_literal (error,
795
0
                           G_IO_ERROR,
796
0
                           G_IO_ERROR_INVALID_ARGUMENT,
797
0
                           _("Requested seek beyond the end of the stream"));
798
0
      return FALSE;
799
0
    }
800
801
0
  priv->pos = absolute;
802
803
0
  return TRUE;
804
0
}
805
806
static gboolean
807
g_memory_output_stream_can_truncate (GSeekable *seekable)
808
0
{
809
0
  GMemoryOutputStream *ostream;
810
0
  GMemoryOutputStreamPrivate *priv;
811
812
0
  ostream = G_MEMORY_OUTPUT_STREAM (seekable);
813
0
  priv = ostream->priv;
814
815
  /* We do not allow truncation of fixed-sized streams */
816
0
  return priv->realloc_fn != NULL;
817
0
}
818
819
static gboolean
820
g_memory_output_stream_truncate (GSeekable     *seekable,
821
                                 goffset        offset,
822
                                 GCancellable  *cancellable,
823
                                 GError       **error)
824
0
{
825
0
  GMemoryOutputStream *ostream = G_MEMORY_OUTPUT_STREAM (seekable);
826
827
0
  if (!array_resize (ostream, offset, FALSE, error))
828
0
    return FALSE;
829
830
0
  ostream->priv->valid_len = offset;
831
832
0
  return TRUE;
833
0
}
834
835
static gboolean
836
g_memory_output_stream_is_writable (GPollableOutputStream *stream)
837
0
{
838
0
  return TRUE;
839
0
}
840
841
static GSource *
842
g_memory_output_stream_create_source (GPollableOutputStream *stream,
843
                                      GCancellable          *cancellable)
844
0
{
845
0
  GSource *base_source, *pollable_source;
846
847
0
  base_source = g_timeout_source_new (0);
848
0
  pollable_source = g_pollable_source_new_full (stream, base_source, cancellable);
849
0
  g_source_unref (base_source);
850
851
0
  return pollable_source;
852
0
}