Trivial doc fixes
[platform/upstream/glib.git] / gio / gmemoryoutputstream.c
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 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, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Christian Kellner <gicmo@gnome.org>
21  */
22
23 #include "config.h"
24 #include "gmemoryoutputstream.h"
25 #include "goutputstream.h"
26 #include "gseekable.h"
27 #include "gsimpleasyncresult.h"
28 #include "string.h"
29 #include "glibintl.h"
30
31 #include "gioalias.h"
32
33 /**
34  * SECTION:gmemoryoutputstream
35  * @short_description: Streaming output operations on memory chunks
36  * @include: gio/gio.h
37  * @see_also: #GMemoryInputStream
38  *
39  * #GMemoryOutputStream is a class for using arbitrary
40  * memory chunks as output for GIO streaming output operations.
41  *
42  */
43
44 #define MIN_ARRAY_SIZE  16
45
46 struct _GMemoryOutputStreamPrivate {
47   
48   gpointer       data;
49   gsize          len;
50
51   goffset        pos;
52
53   GReallocFunc   realloc_fn;
54   GDestroyNotify destroy;
55 };
56
57 static void     g_memory_output_stream_finalize     (GObject      *object);
58
59 static gssize   g_memory_output_stream_write       (GOutputStream *stream,
60                                                     const void    *buffer,
61                                                     gsize          count,
62                                                     GCancellable  *cancellable,
63                                                     GError       **error);
64
65 static gboolean g_memory_output_stream_close       (GOutputStream  *stream,
66                                                     GCancellable   *cancellable,
67                                                     GError        **error);
68
69 static void     g_memory_output_stream_write_async  (GOutputStream        *stream,
70                                                      const void           *buffer,
71                                                      gsize                 count,
72                                                      int                   io_priority,
73                                                      GCancellable         *cancellable,
74                                                      GAsyncReadyCallback   callback,
75                                                      gpointer              data);
76 static gssize   g_memory_output_stream_write_finish (GOutputStream        *stream,
77                                                      GAsyncResult         *result,
78                                                      GError              **error);
79 static void     g_memory_output_stream_close_async  (GOutputStream        *stream,
80                                                      int                   io_priority,
81                                                      GCancellable         *cancellable,
82                                                      GAsyncReadyCallback   callback,
83                                                      gpointer              data);
84 static gboolean g_memory_output_stream_close_finish (GOutputStream        *stream,
85                                                      GAsyncResult         *result,
86                                                      GError              **error);
87
88 static void     g_memory_output_stream_seekable_iface_init (GSeekableIface  *iface);
89 static goffset  g_memory_output_stream_tell                (GSeekable       *seekable);
90 static gboolean g_memory_output_stream_can_seek            (GSeekable       *seekable);
91 static gboolean g_memory_output_stream_seek                (GSeekable       *seekable,
92                                                            goffset          offset,
93                                                            GSeekType        type,
94                                                            GCancellable    *cancellable,
95                                                            GError         **error);
96 static gboolean g_memory_output_stream_can_truncate        (GSeekable       *seekable);
97 static gboolean g_memory_output_stream_truncate            (GSeekable       *seekable,
98                                                            goffset          offset,
99                                                            GCancellable    *cancellable,
100                                                            GError         **error);
101
102 G_DEFINE_TYPE_WITH_CODE (GMemoryOutputStream, g_memory_output_stream, G_TYPE_OUTPUT_STREAM,
103                          G_IMPLEMENT_INTERFACE (G_TYPE_SEEKABLE,
104                                                 g_memory_output_stream_seekable_iface_init))
105
106
107 static void
108 g_memory_output_stream_class_init (GMemoryOutputStreamClass *klass)
109 {
110   GOutputStreamClass *ostream_class;
111   GObjectClass *gobject_class;
112
113   g_type_class_add_private (klass, sizeof (GMemoryOutputStreamPrivate));
114
115   gobject_class = G_OBJECT_CLASS (klass);
116   gobject_class->finalize = g_memory_output_stream_finalize;
117
118   ostream_class = G_OUTPUT_STREAM_CLASS (klass);
119
120   ostream_class->write_fn = g_memory_output_stream_write;
121   ostream_class->close_fn = g_memory_output_stream_close;
122   ostream_class->write_async  = g_memory_output_stream_write_async;
123   ostream_class->write_finish = g_memory_output_stream_write_finish;
124   ostream_class->close_async  = g_memory_output_stream_close_async;
125   ostream_class->close_finish = g_memory_output_stream_close_finish;
126 }
127
128 static void
129 g_memory_output_stream_finalize (GObject *object)
130 {
131   GMemoryOutputStream        *stream;
132   GMemoryOutputStreamPrivate *priv;
133
134   stream = G_MEMORY_OUTPUT_STREAM (object);
135   priv = stream->priv;
136   
137   if (priv->destroy)
138     priv->destroy (priv->data);
139
140   G_OBJECT_CLASS (g_memory_output_stream_parent_class)->finalize (object);
141 }
142
143 static void
144 g_memory_output_stream_seekable_iface_init (GSeekableIface *iface)
145 {
146   iface->tell         = g_memory_output_stream_tell;
147   iface->can_seek     = g_memory_output_stream_can_seek;
148   iface->seek         = g_memory_output_stream_seek;
149   iface->can_truncate = g_memory_output_stream_can_truncate;
150   iface->truncate_fn  = g_memory_output_stream_truncate;
151 }
152
153
154 static void
155 g_memory_output_stream_init (GMemoryOutputStream *stream)
156 {
157   stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (stream,
158                                               G_TYPE_MEMORY_OUTPUT_STREAM,
159                                               GMemoryOutputStreamPrivate);
160 }
161
162 /**
163  * g_memory_output_stream_new:
164  * @data: pointer to a chunk of memory to use, or %NULL
165  * @len: the size of @data
166  * @realloc_fn: a function with realloc() semantics to be called when 
167  *     @data needs to be grown, or %NULL
168  * @destroy: a function to be called on @data when the stream is finalized,
169  *     or %NULL
170  *
171  * Creates a new #GMemoryOutputStream. 
172  *
173  * If @data is non-%NULL, the stream  will use that for its internal storage.
174  * If @realloc_fn is non-%NULL, it will be used for resizing the internal
175  * storage when necessary. To construct a fixed-size output stream, 
176  * pass %NULL as @realloc_fn.
177  * |[
178  * /&ast; a stream that can grow &ast;/
179  * stream = g_memory_output_stream_new (NULL, 0, realloc, free);
180  *
181  * /&ast; a fixed-size stream &ast;/
182  * data = malloc (200);
183  * stream2 = g_memory_output_stream_new (data, 200, NULL, free);
184  * ]|
185  *
186  * Return value: A newly created #GMemoryOutputStream object.
187  **/
188 GOutputStream *
189 g_memory_output_stream_new (gpointer       data,
190                             gsize          len,
191                             GReallocFunc   realloc_fn,
192                             GDestroyNotify destroy)
193 {
194   GOutputStream *stream;
195   GMemoryOutputStreamPrivate *priv;
196
197   stream = g_object_new (G_TYPE_MEMORY_OUTPUT_STREAM, NULL);
198
199   priv = G_MEMORY_OUTPUT_STREAM (stream)->priv;
200
201   priv->data = data;
202   priv->len = len;
203   priv->realloc_fn = realloc_fn;
204   priv->destroy = destroy;
205
206   priv->pos = 0;
207
208   return stream;
209 }
210
211 /**
212  * g_memory_output_stream_get_data:
213  * @ostream: a #GMemoryOutputStream
214  *
215  * Gets any loaded data from the @ostream. 
216  *
217  * Note that the returned pointer may become invalid on the next 
218  * write or truncate operation on the stream. 
219  * 
220  * Returns: pointer to the stream's data
221  **/
222 gpointer
223 g_memory_output_stream_get_data (GMemoryOutputStream *ostream)
224 {
225   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), NULL);
226
227   return ostream->priv->data;
228 }
229
230 /**
231  * g_memory_output_stream_get_size:
232  * @ostream: a #GMemoryOutputStream
233  *
234  * Gets the size of the currently allocated data area (availible from
235  * g_memory_output_stream_get_data()). If the stream isn't
236  * growable (no realloc was passed to g_memory_output_stream_new()) then
237  * this is the maximum size of the stream and further writes
238  * will return %G_IO_ERROR_NO_SPACE.
239  *
240  * Note that for growable streams the returned size may become invalid on
241  * the next write or truncate operation on the stream.
242  *
243  * If you want the number of bytes currently written to the stream, use
244  * g_memory_output_stream_get_data_size().
245  * 
246  * Returns: the number of bytes allocated for the data buffer
247  */
248 gsize
249 g_memory_output_stream_get_size (GMemoryOutputStream *ostream)
250 {
251   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
252   
253   return ostream->priv->len;
254 }
255
256 /**
257  * g_memory_output_stream_get_data_size:
258  * @ostream: a #GMemoryOutputStream
259  *
260  * Returns the number of bytes from the start up
261  * to including the last byte written in the stream
262  * that has not been truncated away.
263  * 
264  * Returns: the number of bytes written to the stream
265  *
266  * Since: 2.18
267  */
268 gsize
269 g_memory_output_stream_get_data_size (GMemoryOutputStream *ostream)
270 {
271   g_return_val_if_fail (G_IS_MEMORY_OUTPUT_STREAM (ostream), 0);
272   
273   return ostream->priv->pos;
274 }
275
276
277 static gboolean
278 array_check_boundary (GMemoryOutputStream  *stream,
279                       goffset               size,
280                       GError              **error)
281 {
282   if (size > G_MAXUINT)
283     {
284       g_set_error_literal (error,
285                            G_IO_ERROR,
286                            G_IO_ERROR_FAILED,
287                            _("Reached maximum data array limit"));
288
289       return FALSE;
290     }
291
292   return TRUE;
293 }
294
295 static gboolean
296 array_resize (GMemoryOutputStream  *ostream,
297               gsize                 size,
298               gboolean              allow_partial,
299               GError              **error)
300 {
301   GMemoryOutputStreamPrivate *priv;
302   gpointer data;
303   gsize len;
304
305   priv = ostream->priv;
306
307   if (!array_check_boundary (ostream, size, error))
308     return FALSE;
309
310   if (priv->len == size)
311     return TRUE;
312
313   if (!priv->realloc_fn)
314     {
315       if (allow_partial &&
316           priv->pos < priv->len)
317         return TRUE; /* Short write */
318       
319       g_set_error_literal (error,
320                            G_IO_ERROR,
321                            G_IO_ERROR_NO_SPACE,
322                            _("Memory output stream not resizable"));
323       return FALSE;
324     }
325
326   len = priv->len;
327   data = priv->realloc_fn (priv->data, size);
328
329   if (!data) 
330     {
331       if (allow_partial &&
332           priv->pos < priv->len)
333         return TRUE; /* Short write */
334       
335       g_set_error_literal (error,
336                            G_IO_ERROR,
337                            G_IO_ERROR_NO_SPACE,
338                            _("Failed to resize memory output stream"));
339       return FALSE;
340     }
341
342   if (size > len)
343     memset ((guint8 *)data + len, 0, size - len);
344
345   priv->data = data;
346   priv->len = size;
347   
348   return TRUE;
349 }
350
351 static gint
352 g_nearest_pow (gint num)
353 {
354   gint n = 1;
355
356   while (n < num)
357     n <<= 1;
358
359   return n;
360 }
361
362 static gssize
363 g_memory_output_stream_write (GOutputStream  *stream,
364                               const void     *buffer,
365                               gsize           count,
366                               GCancellable   *cancellable,
367                               GError        **error)
368 {
369   GMemoryOutputStream        *ostream;
370   GMemoryOutputStreamPrivate *priv;
371   guint8   *dest;
372   gsize new_size;
373
374   ostream = G_MEMORY_OUTPUT_STREAM (stream);
375   priv = ostream->priv;
376
377   if (count == 0)
378     return 0;
379
380   if (priv->pos + count > priv->len) 
381     {
382       /* At least enought to fit the write, rounded up
383          for greater than linear growth */
384       new_size = g_nearest_pow (priv->pos + count);
385       new_size = MAX (new_size, MIN_ARRAY_SIZE);
386       
387       if (!array_resize (ostream, new_size, TRUE, error))
388         return -1;
389     }
390
391   /* Make sure we handle short writes if the array_resize
392      only added part of the required memory */
393   count = MIN (count, priv->len - priv->pos);
394   
395   dest = (guint8 *)priv->data + priv->pos;
396   memcpy (dest, buffer, count); 
397   priv->pos += count;
398
399   return count;
400 }
401
402 static gboolean
403 g_memory_output_stream_close (GOutputStream  *stream,
404                               GCancellable   *cancellable,
405                               GError        **error)
406 {
407   return TRUE;
408 }
409
410 static void
411 g_memory_output_stream_write_async (GOutputStream       *stream,
412                                     const void          *buffer,
413                                     gsize                count,
414                                     int                  io_priority,
415                                     GCancellable        *cancellable,
416                                     GAsyncReadyCallback  callback,
417                                     gpointer             data)
418 {
419   GSimpleAsyncResult *simple;
420   gssize nwritten;
421
422   nwritten = g_memory_output_stream_write (stream,
423                                            buffer,
424                                            count,
425                                            cancellable,
426                                            NULL);
427  
428
429   simple = g_simple_async_result_new (G_OBJECT (stream),
430                                       callback,
431                                       data,
432                                       g_memory_output_stream_write_async);
433   
434   g_simple_async_result_set_op_res_gssize (simple, nwritten); 
435   g_simple_async_result_complete_in_idle (simple);
436   g_object_unref (simple);
437 }
438
439 static gssize
440 g_memory_output_stream_write_finish (GOutputStream  *stream,
441                                      GAsyncResult   *result,
442                                      GError        **error)
443 {
444   GSimpleAsyncResult *simple;
445   gssize nwritten;
446
447   simple = G_SIMPLE_ASYNC_RESULT (result);
448   
449   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == 
450                   g_memory_output_stream_write_async);
451
452   nwritten = g_simple_async_result_get_op_res_gssize (simple);
453
454   return nwritten;
455 }
456
457 static void
458 g_memory_output_stream_close_async (GOutputStream       *stream,
459                                     int                  io_priority,
460                                     GCancellable        *cancellable,
461                                     GAsyncReadyCallback  callback,
462                                     gpointer             data)
463 {
464   GSimpleAsyncResult *simple;
465
466   simple = g_simple_async_result_new (G_OBJECT (stream),
467                                       callback,
468                                       data,
469                                       g_memory_output_stream_close_async);
470
471
472   /* will always return TRUE */
473   g_memory_output_stream_close (stream, cancellable, NULL);
474   
475   g_simple_async_result_complete_in_idle (simple);
476   g_object_unref (simple);
477 }
478
479 static gboolean
480 g_memory_output_stream_close_finish (GOutputStream  *stream,
481                                      GAsyncResult   *result,
482                                      GError        **error)
483 {
484   GSimpleAsyncResult *simple;
485
486   simple = G_SIMPLE_ASYNC_RESULT (result);
487
488   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == 
489                   g_memory_output_stream_close_async);
490
491   return TRUE;
492 }
493
494 static goffset
495 g_memory_output_stream_tell (GSeekable *seekable)
496 {
497   GMemoryOutputStream *stream;
498   GMemoryOutputStreamPrivate *priv;
499
500   stream = G_MEMORY_OUTPUT_STREAM (seekable);
501   priv = stream->priv;
502
503   return priv->pos;
504 }
505
506 static gboolean
507 g_memory_output_stream_can_seek (GSeekable *seekable)
508 {
509   return TRUE;
510 }
511
512 static gboolean
513 g_memory_output_stream_seek (GSeekable    *seekable,
514                             goffset        offset,
515                             GSeekType      type,
516                             GCancellable  *cancellable,
517                             GError       **error)
518 {
519   GMemoryOutputStream        *stream;
520   GMemoryOutputStreamPrivate *priv;
521   goffset absolute;
522
523   stream = G_MEMORY_OUTPUT_STREAM (seekable);
524   priv = stream->priv;
525
526   switch (type) 
527     {
528     case G_SEEK_CUR:
529       absolute = priv->pos + offset;
530       break;
531
532     case G_SEEK_SET:
533       absolute = offset;
534       break;
535
536     case G_SEEK_END:
537       absolute = priv->len + offset;
538       break;
539   
540     default:
541       g_set_error_literal (error,
542                            G_IO_ERROR,
543                            G_IO_ERROR_INVALID_ARGUMENT,
544                            _("Invalid GSeekType supplied"));
545
546       return FALSE;
547     }
548
549   if (absolute < 0) 
550     {
551       g_set_error_literal (error,
552                            G_IO_ERROR,
553                            G_IO_ERROR_INVALID_ARGUMENT,
554                            _("Invalid seek request"));
555       return FALSE;
556     }
557
558   if (!array_check_boundary (stream, absolute, error)) 
559     return FALSE;  
560
561   priv->pos = absolute;
562
563   return TRUE;
564 }
565
566 static gboolean
567 g_memory_output_stream_can_truncate (GSeekable *seekable)
568 {
569   GMemoryOutputStream *ostream;
570   GMemoryOutputStreamPrivate *priv;
571
572   ostream = G_MEMORY_OUTPUT_STREAM (seekable);
573   priv = ostream->priv;
574
575   return priv->realloc_fn != NULL;
576 }
577
578 static gboolean
579 g_memory_output_stream_truncate (GSeekable     *seekable,
580                                  goffset        offset,
581                                  GCancellable  *cancellable,
582                                  GError       **error)
583 {
584   GMemoryOutputStream *ostream;
585   GMemoryOutputStreamPrivate *priv;
586
587   ostream = G_MEMORY_OUTPUT_STREAM (seekable);
588   priv = ostream->priv;
589  
590   if (!array_resize (ostream, offset, FALSE, error))
591     return FALSE;
592
593   return TRUE;
594 }
595
596 #define __G_MEMORY_OUTPUT_STREAM_C__
597 #include "gioaliasdef.c"