GMemoryInputStream: Add API to accept GBytes
[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 "gsimpleasyncresult.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  * Since: 2.34
223  **/
224 GInputStream *
225 g_memory_input_stream_new_from_bytes (GBytes  *bytes)
226 {
227   
228   GInputStream *stream;
229
230   stream = g_memory_input_stream_new ();
231
232   g_memory_input_stream_add_bytes (G_MEMORY_INPUT_STREAM (stream),
233                                    bytes);
234
235   return stream;
236 }
237
238 /**
239  * g_memory_input_stream_add_data:
240  * @stream: a #GMemoryInputStream
241  * @data: (array length=len) (element-type guint8) (transfer full): input data
242  * @len: length of the data, may be -1 if @data is a nul-terminated string
243  * @destroy: (allow-none): function that is called to free @data, or %NULL
244  *
245  * Appends @data to data that can be read from the input stream
246  */
247 void
248 g_memory_input_stream_add_data (GMemoryInputStream *stream,
249                                 const void         *data,
250                                 gssize              len,
251                                 GDestroyNotify      destroy)
252 {
253   GBytes *bytes;
254
255   if (len == -1)
256     len = strlen (data);
257
258   /* It's safe to discard the const here because we're chaining the
259    * destroy callback.
260    */
261   bytes = g_bytes_new_with_free_func (data, len, destroy, (void*)data);
262
263   g_memory_input_stream_add_bytes (stream, bytes);
264   
265   g_bytes_unref (bytes);
266 }
267
268 /**
269  * g_memory_input_stream_add_bytes:
270  * @stream: a #GMemoryInputStream
271  * @bytes: input data
272  *
273  * Appends @bytes to data that can be read from the input stream.
274  *
275  * Since: 2.34
276  */
277 void
278 g_memory_input_stream_add_bytes (GMemoryInputStream *stream,
279                                  GBytes             *bytes)
280 {
281   GMemoryInputStreamPrivate *priv;
282  
283   g_return_if_fail (G_IS_MEMORY_INPUT_STREAM (stream));
284   g_return_if_fail (bytes != NULL);
285
286   priv = stream->priv;
287
288   priv->chunks = g_slist_append (priv->chunks, g_bytes_ref (bytes));
289   priv->len += g_bytes_get_size (bytes);
290 }
291
292 static gssize
293 g_memory_input_stream_read (GInputStream  *stream,
294                             void          *buffer,
295                             gsize          count,
296                             GCancellable  *cancellable,
297                             GError       **error)
298 {
299   GMemoryInputStream *memory_stream;
300   GMemoryInputStreamPrivate *priv;
301   GSList *l;
302   GBytes *chunk;
303   gsize len;
304   gsize offset, start, rest, size;
305
306   memory_stream = G_MEMORY_INPUT_STREAM (stream);
307   priv = memory_stream->priv;
308
309   count = MIN (count, priv->len - priv->pos);
310
311   offset = 0;
312   for (l = priv->chunks; l; l = l->next) 
313     {
314       chunk = (GBytes *)l->data;
315       len = g_bytes_get_size (chunk);
316
317       if (offset + len > priv->pos)
318         break;
319
320       offset += len;
321     }
322   
323   start = priv->pos - offset;
324   rest = count;
325
326   for (; l && rest > 0; l = l->next)
327     {
328       const guint8* chunk_data;
329       chunk = (GBytes *)l->data;
330
331       chunk_data = g_bytes_get_data (chunk, &len);
332
333       size = MIN (rest, len - start);
334
335       memcpy ((guint8 *)buffer + (count - rest), chunk_data + start, size);
336       rest -= size;
337
338       start = 0;
339     }
340
341   priv->pos += count;
342
343   return count;
344 }
345
346 static gssize
347 g_memory_input_stream_skip (GInputStream  *stream,
348                             gsize          count,
349                             GCancellable  *cancellable,
350                             GError       **error)
351 {
352   GMemoryInputStream *memory_stream;
353   GMemoryInputStreamPrivate *priv;
354
355   memory_stream = G_MEMORY_INPUT_STREAM (stream);
356   priv = memory_stream->priv;
357
358   count = MIN (count, priv->len - priv->pos);
359   priv->pos += count;
360
361   return count;
362 }
363
364 static gboolean
365 g_memory_input_stream_close (GInputStream  *stream,
366                              GCancellable  *cancellable,
367                              GError       **error)
368 {
369   return TRUE;
370 }
371
372 static void
373 g_memory_input_stream_skip_async (GInputStream        *stream,
374                                   gsize                count,
375                                   int                  io_priority,
376                                   GCancellable        *cancellable,
377                                   GAsyncReadyCallback  callback,
378                                   gpointer             user_data)
379 {
380   GSimpleAsyncResult *simple;
381   gssize nskipped;
382
383   nskipped = g_input_stream_skip (stream, count, cancellable, NULL);
384   simple = g_simple_async_result_new (G_OBJECT (stream),
385                                       callback,
386                                       user_data,
387                                       g_memory_input_stream_skip_async);
388   g_simple_async_result_set_op_res_gssize (simple, nskipped);
389   g_simple_async_result_complete_in_idle (simple);
390   g_object_unref (simple);
391 }
392
393 static gssize
394 g_memory_input_stream_skip_finish (GInputStream  *stream,
395                                    GAsyncResult  *result,
396                                    GError       **error)
397 {
398   GSimpleAsyncResult *simple;
399   gssize nskipped;
400
401   simple = G_SIMPLE_ASYNC_RESULT (result);
402   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_memory_input_stream_skip_async);
403   
404   nskipped = g_simple_async_result_get_op_res_gssize (simple);
405   return nskipped;
406 }
407
408 static void
409 g_memory_input_stream_close_async (GInputStream        *stream,
410                                    int                  io_priority,
411                                    GCancellable        *cancellable,
412                                    GAsyncReadyCallback  callback,
413                                    gpointer             user_data)
414 {
415   GSimpleAsyncResult *simple;
416   
417   simple = g_simple_async_result_new (G_OBJECT (stream),
418                                       callback,
419                                       user_data,
420                                       g_memory_input_stream_close_async);
421   g_simple_async_result_complete_in_idle (simple);
422   g_object_unref (simple);
423 }
424
425 static gboolean
426 g_memory_input_stream_close_finish (GInputStream  *stream,
427                                     GAsyncResult  *result,
428                                     GError       **error)
429 {
430   return TRUE;
431 }
432
433 static goffset
434 g_memory_input_stream_tell (GSeekable *seekable)
435 {
436   GMemoryInputStream *memory_stream;
437   GMemoryInputStreamPrivate *priv;
438
439   memory_stream = G_MEMORY_INPUT_STREAM (seekable);
440   priv = memory_stream->priv;
441
442   return priv->pos;
443 }
444
445 static
446 gboolean g_memory_input_stream_can_seek (GSeekable *seekable)
447 {
448   return TRUE;
449 }
450
451 static gboolean
452 g_memory_input_stream_seek (GSeekable     *seekable,
453                             goffset        offset,
454                             GSeekType      type,
455                             GCancellable  *cancellable,
456                             GError       **error)
457 {
458   GMemoryInputStream *memory_stream;
459   GMemoryInputStreamPrivate *priv;
460   goffset absolute;
461
462   memory_stream = G_MEMORY_INPUT_STREAM (seekable);
463   priv = memory_stream->priv;
464
465   switch (type) 
466     {
467     case G_SEEK_CUR:
468       absolute = priv->pos + offset;
469       break;
470
471     case G_SEEK_SET:
472       absolute = offset;
473       break;
474
475     case G_SEEK_END:
476       absolute = priv->len + offset;
477       break;
478   
479     default:
480       g_set_error_literal (error,
481                            G_IO_ERROR,
482                            G_IO_ERROR_INVALID_ARGUMENT,
483                            _("Invalid GSeekType supplied"));
484
485       return FALSE;
486     }
487
488   if (absolute < 0 || absolute > priv->len)
489     {
490       g_set_error_literal (error,
491                            G_IO_ERROR,
492                            G_IO_ERROR_INVALID_ARGUMENT,
493                            _("Invalid seek request"));
494       return FALSE;
495     }
496
497   priv->pos = absolute;
498
499   return TRUE;
500 }
501
502 static gboolean
503 g_memory_input_stream_can_truncate (GSeekable *seekable)
504 {
505   return FALSE;
506 }
507
508 static gboolean
509 g_memory_input_stream_truncate (GSeekable     *seekable,
510                                 goffset        offset,
511                                 GCancellable  *cancellable,
512                                 GError       **error)
513 {
514   g_set_error_literal (error,
515                        G_IO_ERROR,
516                        G_IO_ERROR_NOT_SUPPORTED,
517                        _("Cannot truncate GMemoryInputStream"));
518   return FALSE;
519 }
520
521 static gboolean
522 g_memory_input_stream_is_readable (GPollableInputStream *stream)
523 {
524   return TRUE;
525 }
526
527 static GSource *
528 g_memory_input_stream_create_source (GPollableInputStream *stream,
529                                      GCancellable         *cancellable)
530 {
531   GSource *base_source, *pollable_source;
532
533   base_source = g_timeout_source_new (0);
534   pollable_source = g_pollable_source_new_full (stream, base_source,
535                                                 cancellable);
536   g_source_unref (base_source);
537
538   return pollable_source;
539 }