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