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