GMemoryInputStream/GMemoryOutputStream: fix bug in previous commit
[platform/upstream/glib.git] / gio / gmemoryinputstream.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 "gmemoryinputstream.h"
25 #include "ginputstream.h"
26 #include "gseekable.h"
27 #include "string.h"
28 #include "gsimpleasyncresult.h"
29 #include "gioerror.h"
30 #include "glibintl.h"
31
32
33 /**
34  * SECTION:gmemoryinputstream
35  * @short_description: Streaming input operations on memory chunks
36  * @include: gio/gio.h
37  * @see_also: #GMemoryOutputStream
38  *
39  * #GMemoryInputStream is a class for using arbitrary
40  * memory chunks as input for GIO streaming input operations.
41  *
42  */
43
44 typedef struct _Chunk Chunk;
45
46 struct _Chunk {
47   guint8         *data;
48   gsize           len;
49   GDestroyNotify  destroy;
50 };
51
52 struct _GMemoryInputStreamPrivate {
53   GSList *chunks;
54   gsize   len;
55   gsize   pos;
56 };
57
58 static gssize   g_memory_input_stream_read         (GInputStream         *stream,
59                                                     void                 *buffer,
60                                                     gsize                 count,
61                                                     GCancellable         *cancellable,
62                                                     GError              **error);
63 static gssize   g_memory_input_stream_skip         (GInputStream         *stream,
64                                                     gsize                 count,
65                                                     GCancellable         *cancellable,
66                                                     GError              **error);
67 static gboolean g_memory_input_stream_close        (GInputStream         *stream,
68                                                     GCancellable         *cancellable,
69                                                     GError              **error);
70 static void     g_memory_input_stream_read_async   (GInputStream         *stream,
71                                                     void                 *buffer,
72                                                     gsize                 count,
73                                                     int                   io_priority,
74                                                     GCancellable         *cancellable,
75                                                     GAsyncReadyCallback   callback,
76                                                     gpointer              user_data);
77 static gssize   g_memory_input_stream_read_finish  (GInputStream         *stream,
78                                                     GAsyncResult         *result,
79                                                     GError              **error);
80 static void     g_memory_input_stream_skip_async   (GInputStream         *stream,
81                                                     gsize                 count,
82                                                     int                   io_priority,
83                                                     GCancellable         *cancellabl,
84                                                     GAsyncReadyCallback   callback,
85                                                     gpointer              datae);
86 static gssize   g_memory_input_stream_skip_finish  (GInputStream         *stream,
87                                                     GAsyncResult         *result,
88                                                     GError              **error);
89 static void     g_memory_input_stream_close_async  (GInputStream         *stream,
90                                                     int                   io_priority,
91                                                     GCancellable         *cancellabl,
92                                                     GAsyncReadyCallback   callback,
93                                                     gpointer              data);
94 static gboolean g_memory_input_stream_close_finish (GInputStream         *stream,
95                                                     GAsyncResult         *result,
96                                                     GError              **error);
97
98 static void     g_memory_input_stream_seekable_iface_init (GSeekableIface  *iface);
99 static goffset  g_memory_input_stream_tell                (GSeekable       *seekable);
100 static gboolean g_memory_input_stream_can_seek            (GSeekable       *seekable);
101 static gboolean g_memory_input_stream_seek                (GSeekable       *seekable,
102                                                            goffset          offset,
103                                                            GSeekType        type,
104                                                            GCancellable    *cancellable,
105                                                            GError         **error);
106 static gboolean g_memory_input_stream_can_truncate        (GSeekable       *seekable);
107 static gboolean g_memory_input_stream_truncate            (GSeekable       *seekable,
108                                                            goffset          offset,
109                                                            GCancellable    *cancellable,
110                                                            GError         **error);
111 static void     g_memory_input_stream_finalize            (GObject         *object);
112
113 G_DEFINE_TYPE_WITH_CODE (GMemoryInputStream, g_memory_input_stream, G_TYPE_INPUT_STREAM,
114                          G_IMPLEMENT_INTERFACE (G_TYPE_SEEKABLE,
115                                                 g_memory_input_stream_seekable_iface_init))
116
117
118 static void
119 g_memory_input_stream_class_init (GMemoryInputStreamClass *klass)
120 {
121   GObjectClass *object_class;
122   GInputStreamClass *istream_class;
123
124   g_type_class_add_private (klass, sizeof (GMemoryInputStreamPrivate));
125
126   object_class = G_OBJECT_CLASS (klass);
127   object_class->finalize     = g_memory_input_stream_finalize;
128   
129   istream_class = G_INPUT_STREAM_CLASS (klass);
130   istream_class->read_fn  = g_memory_input_stream_read;
131   istream_class->skip  = g_memory_input_stream_skip;
132   istream_class->close_fn = g_memory_input_stream_close;
133
134   istream_class->read_async  = g_memory_input_stream_read_async;
135   istream_class->read_finish  = g_memory_input_stream_read_finish;
136   istream_class->skip_async  = g_memory_input_stream_skip_async;
137   istream_class->skip_finish  = g_memory_input_stream_skip_finish;
138   istream_class->close_async = g_memory_input_stream_close_async;
139   istream_class->close_finish = g_memory_input_stream_close_finish;
140 }
141
142 static void
143 free_chunk (gpointer data, 
144             gpointer user_data)
145 {
146   Chunk *chunk = data;
147
148   if (chunk->destroy)
149     chunk->destroy (chunk->data);
150
151   g_slice_free (Chunk, chunk);
152 }
153
154 static void
155 g_memory_input_stream_finalize (GObject *object)
156 {
157   GMemoryInputStream        *stream;
158   GMemoryInputStreamPrivate *priv;
159
160   stream = G_MEMORY_INPUT_STREAM (object);
161   priv = stream->priv;
162
163   g_slist_foreach (priv->chunks, free_chunk, NULL);
164   g_slist_free (priv->chunks);
165
166   G_OBJECT_CLASS (g_memory_input_stream_parent_class)->finalize (object);
167 }
168
169 static void
170 g_memory_input_stream_seekable_iface_init (GSeekableIface *iface)
171 {
172   iface->tell         = g_memory_input_stream_tell;
173   iface->can_seek     = g_memory_input_stream_can_seek;
174   iface->seek         = g_memory_input_stream_seek;
175   iface->can_truncate = g_memory_input_stream_can_truncate;
176   iface->truncate_fn  = g_memory_input_stream_truncate;
177 }
178
179 static void
180 g_memory_input_stream_init (GMemoryInputStream *stream)
181 {
182   stream->priv = G_TYPE_INSTANCE_GET_PRIVATE (stream,
183                                               G_TYPE_MEMORY_INPUT_STREAM,
184                                               GMemoryInputStreamPrivate);
185 }
186
187 /**
188  * g_memory_input_stream_new:
189  *
190  * Creates a new empty #GMemoryInputStream. 
191  *
192  * Returns: a new #GInputStream
193  */
194 GInputStream *
195 g_memory_input_stream_new (void)
196 {
197   GInputStream *stream;
198
199   stream = g_object_new (G_TYPE_MEMORY_INPUT_STREAM, NULL);
200
201   return stream;
202 }
203
204 /**
205  * g_memory_input_stream_new_from_data:
206  * @data: (array length=len) (element-type guint8): input data
207  * @len: length of the data, may be -1 if @data is a nul-terminated string
208  * @destroy: (allow-none): function that is called to free @data, or %NULL
209  *
210  * Creates a new #GMemoryInputStream with data in memory of a given size.
211  * 
212  * Returns: new #GInputStream read from @data of @len bytes.
213  **/
214 GInputStream *
215 g_memory_input_stream_new_from_data (const void     *data, 
216                                      gssize          len,
217                                      GDestroyNotify  destroy)
218 {
219   GInputStream *stream;
220
221   stream = g_memory_input_stream_new ();
222
223   g_memory_input_stream_add_data (G_MEMORY_INPUT_STREAM (stream),
224                                   data, len, destroy);
225
226   return stream;
227 }
228
229 /**
230  * g_memory_input_stream_add_data:
231  * @stream: a #GMemoryInputStream
232  * @data: (array length=len) (element-type guint8): input data
233  * @len: length of the data, may be -1 if @data is a nul-terminated string
234  * @destroy: (allow-none): function that is called to free @data, or %NULL
235  *
236  * Appends @data to data that can be read from the input stream
237  */
238 void
239 g_memory_input_stream_add_data (GMemoryInputStream *stream,
240                                 const void         *data,
241                                 gssize              len,
242                                 GDestroyNotify      destroy)
243 {
244   GMemoryInputStreamPrivate *priv;
245   Chunk *chunk;
246  
247   g_return_if_fail (G_IS_MEMORY_INPUT_STREAM (stream));
248   g_return_if_fail (data != NULL);
249
250   priv = stream->priv;
251
252   if (len == -1)
253     len = strlen (data);
254   
255   chunk = g_slice_new (Chunk);
256   chunk->data = (guint8 *)data;
257   chunk->len = len;
258   chunk->destroy = destroy;
259
260   priv->chunks = g_slist_append (priv->chunks, chunk);
261   priv->len += chunk->len;
262 }
263
264 static gssize
265 g_memory_input_stream_read (GInputStream  *stream,
266                             void          *buffer,
267                             gsize          count,
268                             GCancellable  *cancellable,
269                             GError       **error)
270 {
271   GMemoryInputStream *memory_stream;
272   GMemoryInputStreamPrivate *priv;
273   GSList *l;
274   Chunk *chunk;
275   gsize offset, start, rest, size;
276
277   memory_stream = G_MEMORY_INPUT_STREAM (stream);
278   priv = memory_stream->priv;
279
280   count = MIN (count, priv->len - priv->pos);
281
282   offset = 0;
283   for (l = priv->chunks; l; l = l->next) 
284     {
285       chunk = (Chunk *)l->data;
286
287       if (offset + chunk->len > priv->pos)
288         break;
289
290       offset += chunk->len;
291     }
292   
293   start = priv->pos - offset;
294   rest = count;
295
296   for (; l && rest > 0; l = l->next)
297     {
298       chunk = (Chunk *)l->data;
299       size = MIN (rest, chunk->len - start);
300
301       memcpy ((guint8 *)buffer + (count - rest), chunk->data + start, size);
302       rest -= size;
303
304       start = 0;
305     }
306
307   priv->pos += count;
308
309   return count;
310 }
311
312 static gssize
313 g_memory_input_stream_skip (GInputStream  *stream,
314                             gsize          count,
315                             GCancellable  *cancellable,
316                             GError       **error)
317 {
318   GMemoryInputStream *memory_stream;
319   GMemoryInputStreamPrivate *priv;
320
321   memory_stream = G_MEMORY_INPUT_STREAM (stream);
322   priv = memory_stream->priv;
323
324   count = MIN (count, priv->len - priv->pos);
325   priv->pos += count;
326
327   return count;
328 }
329
330 static gboolean
331 g_memory_input_stream_close (GInputStream  *stream,
332                              GCancellable  *cancellable,
333                              GError       **error)
334 {
335   return TRUE;
336 }
337
338 static void
339 g_memory_input_stream_read_async (GInputStream        *stream,
340                                   void                *buffer,
341                                   gsize                count,
342                                   int                  io_priority,
343                                   GCancellable        *cancellable,
344                                   GAsyncReadyCallback  callback,
345                                   gpointer             user_data)
346 {
347   GSimpleAsyncResult *simple;
348   GError *error = NULL;
349   gssize nread;
350
351   nread = G_INPUT_STREAM_GET_CLASS (stream)->read_fn (stream,
352                                                       buffer,
353                                                       count,
354                                                       cancellable,
355                                                       &error);
356   simple = g_simple_async_result_new (G_OBJECT (stream),
357                                       callback,
358                                       user_data,
359                                       g_memory_input_stream_read_async);
360   if (error)
361     g_simple_async_result_take_error (simple, error);
362   else
363     g_simple_async_result_set_op_res_gssize (simple, nread);
364   g_simple_async_result_complete_in_idle (simple);
365   g_object_unref (simple);
366 }
367
368 static gssize
369 g_memory_input_stream_read_finish (GInputStream  *stream,
370                                    GAsyncResult  *result,
371                                    GError       **error)
372 {
373   GSimpleAsyncResult *simple;
374   gssize nread;
375
376   simple = G_SIMPLE_ASYNC_RESULT (result);
377   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_memory_input_stream_read_async);
378   
379   nread = g_simple_async_result_get_op_res_gssize (simple);
380   return nread;
381 }
382
383 static void
384 g_memory_input_stream_skip_async (GInputStream        *stream,
385                                   gsize                count,
386                                   int                  io_priority,
387                                   GCancellable        *cancellable,
388                                   GAsyncReadyCallback  callback,
389                                   gpointer             user_data)
390 {
391   GSimpleAsyncResult *simple;
392   gssize nskipped;
393
394   nskipped = g_input_stream_skip (stream, count, cancellable, NULL);
395   simple = g_simple_async_result_new (G_OBJECT (stream),
396                                       callback,
397                                       user_data,
398                                       g_memory_input_stream_skip_async);
399   g_simple_async_result_set_op_res_gssize (simple, nskipped);
400   g_simple_async_result_complete_in_idle (simple);
401   g_object_unref (simple);
402 }
403
404 static gssize
405 g_memory_input_stream_skip_finish (GInputStream  *stream,
406                                    GAsyncResult  *result,
407                                    GError       **error)
408 {
409   GSimpleAsyncResult *simple;
410   gssize nskipped;
411
412   simple = G_SIMPLE_ASYNC_RESULT (result);
413   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_memory_input_stream_skip_async);
414   
415   nskipped = g_simple_async_result_get_op_res_gssize (simple);
416   return nskipped;
417 }
418
419 static void
420 g_memory_input_stream_close_async (GInputStream        *stream,
421                                    int                  io_priority,
422                                    GCancellable        *cancellable,
423                                    GAsyncReadyCallback  callback,
424                                    gpointer             user_data)
425 {
426   GSimpleAsyncResult *simple;
427   
428   simple = g_simple_async_result_new (G_OBJECT (stream),
429                                       callback,
430                                       user_data,
431                                       g_memory_input_stream_close_async);
432   g_simple_async_result_complete_in_idle (simple);
433   g_object_unref (simple);
434 }
435
436 static gboolean
437 g_memory_input_stream_close_finish (GInputStream  *stream,
438                                     GAsyncResult  *result,
439                                     GError       **error)
440 {
441   return TRUE;
442 }
443
444 static goffset
445 g_memory_input_stream_tell (GSeekable *seekable)
446 {
447   GMemoryInputStream *memory_stream;
448   GMemoryInputStreamPrivate *priv;
449
450   memory_stream = G_MEMORY_INPUT_STREAM (seekable);
451   priv = memory_stream->priv;
452
453   return priv->pos;
454 }
455
456 static
457 gboolean g_memory_input_stream_can_seek (GSeekable *seekable)
458 {
459   return TRUE;
460 }
461
462 static gboolean
463 g_memory_input_stream_seek (GSeekable     *seekable,
464                             goffset        offset,
465                             GSeekType      type,
466                             GCancellable  *cancellable,
467                             GError       **error)
468 {
469   GMemoryInputStream *memory_stream;
470   GMemoryInputStreamPrivate *priv;
471   goffset absolute;
472
473   memory_stream = G_MEMORY_INPUT_STREAM (seekable);
474   priv = memory_stream->priv;
475
476   switch (type) 
477     {
478     case G_SEEK_CUR:
479       absolute = priv->pos + offset;
480       break;
481
482     case G_SEEK_SET:
483       absolute = offset;
484       break;
485
486     case G_SEEK_END:
487       absolute = priv->len + offset;
488       break;
489   
490     default:
491       g_set_error_literal (error,
492                            G_IO_ERROR,
493                            G_IO_ERROR_INVALID_ARGUMENT,
494                            _("Invalid GSeekType supplied"));
495
496       return FALSE;
497     }
498
499   if (absolute < 0 || absolute > priv->len)
500     {
501       g_set_error_literal (error,
502                            G_IO_ERROR,
503                            G_IO_ERROR_INVALID_ARGUMENT,
504                            _("Invalid seek request"));
505       return FALSE;
506     }
507
508   priv->pos = absolute;
509
510   return TRUE;
511 }
512
513 static gboolean
514 g_memory_input_stream_can_truncate (GSeekable *seekable)
515 {
516   return FALSE;
517 }
518
519 static gboolean
520 g_memory_input_stream_truncate (GSeekable     *seekable,
521                                 goffset        offset,
522                                 GCancellable  *cancellable,
523                                 GError       **error)
524 {
525   g_set_error_literal (error,
526                        G_IO_ERROR,
527                        G_IO_ERROR_NOT_SUPPORTED,
528                        _("Cannot truncate GMemoryInputStream"));
529   return FALSE;
530 }