GVariant: use GVariantTypeInfo on internal constructors
[platform/upstream/glib.git] / glib / gbytes.c
1 /*
2  * Copyright © 2009, 2010 Codethink Limited
3  * Copyright © 2011 Collabora Ltd.
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 licence, 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 Public
16  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
17  *
18  * Author: Ryan Lortie <desrt@desrt.ca>
19  *         Stef Walter <stefw@collabora.co.uk>
20  */
21
22 #include "config.h"
23
24 #include "gbytes.h"
25
26 #include <glib/garray.h>
27 #include <glib/gstrfuncs.h>
28 #include <glib/gatomic.h>
29 #include <glib/gslice.h>
30 #include <glib/gtestutils.h>
31 #include <glib/gmem.h>
32 #include <glib/gmessages.h>
33
34 #include <string.h>
35 #include <errno.h>
36 #include <sys/stat.h>
37 #include <sys/types.h>
38
39 #ifdef G_OS_UNIX
40 #include "glib-unix.h"
41 #include <sys/mman.h>
42 #endif
43
44 /**
45  * GBytes:
46  *
47  * A simple refcounted data type representing an immutable sequence of zero or
48  * more bytes from an unspecified origin.
49  *
50  * The purpose of a #GBytes is to keep the memory region that it holds
51  * alive for as long as anyone holds a reference to the bytes.  When
52  * the last reference count is dropped, the memory is released. Multiple
53  * unrelated callers can use byte data in the #GBytes without coordinating
54  * their activities, resting assured that the byte data will not change or
55  * move while they hold a reference.
56  *
57  * A #GBytes can come from many different origins that may have
58  * different procedures for freeing the memory region.  Examples are
59  * memory from g_malloc(), from memory slices, from a #GMappedFile or
60  * memory from other allocators.
61  *
62  * #GBytes work well as keys in #GHashTable. Use g_bytes_equal() and
63  * g_bytes_hash() as parameters to g_hash_table_new() or g_hash_table_new_full().
64  * #GBytes can also be used as keys in a #GTree by passing the g_bytes_compare()
65  * function to g_tree_new().
66  *
67  * The data pointed to by this bytes must not be modified. For a mutable
68  * array of bytes see #GByteArray. Use g_bytes_unref_to_array() to create a
69  * mutable array for a #GBytes sequence. To create an immutable #GBytes from
70  * a mutable #GByteArray, use the g_byte_array_free_to_bytes() function.
71  *
72  * Since: 2.32
73  **/
74
75 struct _GBytes
76 {
77   gsize size;
78   gint  ref_count;
79   gint  type_or_fd;
80 };
81
82 typedef struct
83 {
84   GBytes bytes;
85 #if GLIB_SIZEOF_SIZE_T == 4
86   guint pad;
87 #endif
88
89   guchar data[1];
90 } GBytesInline;
91
92 /* important: the ->data field of GBytesInline should always be 'nicely
93  * aligned'.
94  */
95 G_STATIC_ASSERT (G_STRUCT_OFFSET (GBytesInline, data) % (2 * sizeof (gpointer)) == 0);
96 G_STATIC_ASSERT (G_STRUCT_OFFSET (GBytesInline, data) % 8 == 0);
97
98
99 typedef struct
100 {
101   GBytes   bytes;
102
103   gpointer data;
104 } GBytesData;
105
106 typedef struct
107 {
108   GBytesData     data_bytes;
109
110   GDestroyNotify notify;
111   gpointer       user_data;
112 } GBytesNotify;
113
114 #define G_BYTES_TYPE_INLINE        (-1)
115 #define G_BYTES_TYPE_STATIC        (-2)
116 #define G_BYTES_TYPE_FREE          (-3)
117 #define G_BYTES_TYPE_NOTIFY        (-4)
118
119 /* All bytes are either inline or subtypes of GBytesData */
120 #define G_BYTES_IS_INLINE(bytes)   ((bytes)->type_or_fd == G_BYTES_TYPE_INLINE)
121 #define G_BYTES_IS_DATA(bytes)     (!G_BYTES_IS_INLINE(bytes))
122
123 /* More specific subtypes of GBytesData */
124 #define G_BYTES_IS_STATIC(bytes)   ((bytes)->type_or_fd == G_BYTES_TYPE_STATIC)
125 #define G_BYTES_IS_FREE(bytes)     ((bytes)->type_or_fd == G_BYTES_TYPE_FREE)
126 #define G_BYTES_IS_NOTIFY(bytes)   ((bytes)->type_or_fd == G_BYTES_TYPE_NOTIFY)
127
128 /* we have a memfd if type_or_fd >= 0 */
129 #define G_BYTES_IS_MEMFD(bytes)    ((bytes)->type_or_fd >= 0)
130
131 static gpointer
132 g_bytes_allocate (guint struct_size,
133                   guint type_or_fd,
134                   gsize data_size)
135 {
136   GBytes *bytes;
137
138   bytes = g_slice_alloc (struct_size);
139   bytes->size = data_size;
140   bytes->ref_count = 1;
141   bytes->type_or_fd = type_or_fd;
142
143   return bytes;
144 }
145
146 /**
147  * g_bytes_new:
148  * @data: (transfer none) (array length=size) (element-type guint8) (allow-none):
149  *        the data to be used for the bytes
150  * @size: the size of @data
151  *
152  * Creates a new #GBytes from @data.
153  *
154  * @data is copied. If @size is 0, @data may be %NULL.
155  *
156  * Returns: (transfer full): a new #GBytes
157  *
158  * Since: 2.32
159  */
160 GBytes *
161 g_bytes_new (gconstpointer data,
162              gsize         size)
163 {
164   GBytesInline *bytes;
165
166   g_return_val_if_fail (data != NULL || size == 0, NULL);
167
168   bytes = g_bytes_allocate (G_STRUCT_OFFSET (GBytesInline, data[size]), G_BYTES_TYPE_INLINE, size);
169   memcpy (bytes->data, data, size);
170
171   return (GBytes *) bytes;
172 }
173
174 /**
175  * g_bytes_new_take_zero_copy_fd:
176  * @fd: a file descriptor capable of being zero-copy-safe
177  *
178  * Creates a new #GBytes from @fd.
179  *
180  * @fd must be capable of being made zero-copy-safe.  In concrete terms,
181  * this means that a call to g_unix_fd_ensure_zero_copy_safe() on @fd
182  * will succeed.  This call will be made before returning.
183  *
184  * This call consumes @fd, transferring ownership to the returned
185  * #GBytes.
186  *
187  * Returns: (transfer full): a new #GBytes
188  *
189  * Since: 2.44
190  */
191 #ifdef G_OS_UNIX
192 GBytes *
193 g_bytes_new_take_zero_copy_fd (gint fd)
194 {
195   GBytesData *bytes;
196   struct stat buf;
197
198   g_return_val_if_fail_se (g_unix_fd_ensure_zero_copy_safe (fd), NULL);
199
200   /* We already checked this is a memfd... */
201   g_assert_se (fstat (fd, &buf) == 0);
202
203   bytes = g_bytes_allocate (sizeof (GBytesData), fd, buf.st_size);
204   bytes->data = mmap (NULL, buf.st_size, PROT_READ, MAP_SHARED, fd, 0);
205   if (bytes->data == MAP_FAILED)
206     /* this is similar to malloc() failing, so do the same... */
207     g_error ("mmap() on memfd failed: %s\n", g_strerror (errno));
208
209   return (GBytes *) bytes;
210 }
211 #endif /* G_OS_UNIX */
212
213 /**
214  * g_bytes_new_take:
215  * @data: (transfer full) (array length=size) (element-type guint8) (allow-none):
216           the data to be used for the bytes
217  * @size: the size of @data
218  *
219  * Creates a new #GBytes from @data.
220  *
221  * After this call, @data belongs to the bytes and may no longer be
222  * modified by the caller.  g_free() will be called on @data when the
223  * bytes is no longer in use. Because of this @data must have been created by
224  * a call to g_malloc(), g_malloc0() or g_realloc() or by one of the many
225  * functions that wrap these calls (such as g_new(), g_strdup(), etc).
226  *
227  * For creating #GBytes with memory from other allocators, see
228  * g_bytes_new_with_free_func().
229  *
230  * @data may be %NULL if @size is 0.
231  *
232  * Returns: (transfer full): a new #GBytes
233  *
234  * Since: 2.32
235  */
236 GBytes *
237 g_bytes_new_take (gpointer data,
238                   gsize    size)
239 {
240   GBytesData *bytes;
241
242   bytes = g_bytes_allocate (sizeof (GBytesNotify), G_BYTES_TYPE_FREE, size);
243   bytes->data = data;
244
245   return (GBytes *) bytes;
246 }
247
248 /**
249  * g_bytes_new_static: (skip)
250  * @data: (transfer full) (array length=size) (element-type guint8) (allow-none):
251           the data to be used for the bytes
252  * @size: the size of @data
253  *
254  * Creates a new #GBytes from static data.
255  *
256  * @data must be static (ie: never modified or freed). It may be %NULL if @size
257  * is 0.
258  *
259  * Returns: (transfer full): a new #GBytes
260  *
261  * Since: 2.32
262  */
263 GBytes *
264 g_bytes_new_static (gconstpointer data,
265                     gsize         size)
266 {
267   GBytesData *bytes;
268
269   g_return_val_if_fail (data != NULL || size == 0, NULL);
270
271   bytes = g_bytes_allocate (sizeof (GBytesData), G_BYTES_TYPE_STATIC, size);
272   bytes->data = (gpointer) data;
273
274   return (GBytes *) bytes;
275 }
276
277 /**
278  * g_bytes_new_with_free_func:
279  * @data: (array length=size) (allow-none): the data to be used for the bytes
280  * @size: the size of @data
281  * @free_func: the function to call to release the data
282  * @user_data: data to pass to @free_func
283  *
284  * Creates a #GBytes from @data.
285  *
286  * When the last reference is dropped, @free_func will be called with the
287  * @user_data argument.
288  *
289  * @data must not be modified after this call is made until @free_func has
290  * been called to indicate that the bytes is no longer in use.
291  *
292  * @data may be %NULL if @size is 0.
293  *
294  * Returns: (transfer full): a new #GBytes
295  *
296  * Since: 2.32
297  */
298 GBytes *
299 g_bytes_new_with_free_func (gconstpointer  data,
300                             gsize          size,
301                             GDestroyNotify free_func,
302                             gpointer       user_data)
303 {
304   GBytesNotify *bytes;
305
306   if (!free_func)
307     return g_bytes_new_static (data, size);
308
309   bytes = g_bytes_allocate (sizeof (GBytesNotify), G_BYTES_TYPE_NOTIFY, size);
310   bytes->data_bytes.data = (gpointer) data;
311   bytes->notify = free_func;
312   bytes->user_data = user_data;
313
314   return (GBytes *) bytes;
315 }
316
317 /**
318  * g_bytes_new_from_bytes:
319  * @bytes: a #GBytes
320  * @offset: offset which subsection starts at
321  * @length: length of subsection
322  *
323  * Creates a #GBytes which is a subsection of another #GBytes. The @offset +
324  * @length may not be longer than the size of @bytes.
325  *
326  * A reference to @bytes will be held by the newly created #GBytes until
327  * the byte data is no longer needed.
328  *
329  * Returns: (transfer full): a new #GBytes
330  *
331  * Since: 2.32
332  */
333 GBytes *
334 g_bytes_new_from_bytes (GBytes  *bytes,
335                         gsize    offset,
336                         gsize    length)
337 {
338   /* Note that length may be 0. */
339   g_return_val_if_fail (bytes != NULL, NULL);
340   g_return_val_if_fail (offset <= bytes->size, NULL);
341   g_return_val_if_fail (offset + length <= bytes->size, NULL);
342
343   return g_bytes_new_with_free_func ((gchar *) g_bytes_get_data (bytes, NULL) + offset, length,
344                                      (GDestroyNotify)g_bytes_unref, g_bytes_ref (bytes));
345 }
346
347 /**
348  * g_bytes_get_data:
349  * @bytes: a #GBytes
350  * @size: (out) (allow-none): location to return size of byte data
351  *
352  * Get the byte data in the #GBytes. This data should not be modified.
353  *
354  * This function will always return the same pointer for a given #GBytes.
355  *
356  * %NULL may be returned if @size is 0. This is not guaranteed, as the #GBytes
357  * may represent an empty string with @data non-%NULL and @size as 0. %NULL will
358  * not be returned if @size is non-zero.
359  *
360  * Returns: (transfer none) (array length=size) (type guint8) (allow-none): a pointer to the
361  *          byte data, or %NULL
362  *
363  * Since: 2.32
364  */
365 gconstpointer
366 g_bytes_get_data (GBytes *bytes,
367                   gsize  *size)
368 {
369   g_return_val_if_fail (bytes != NULL, NULL);
370
371   if (size)
372     *size = bytes->size;
373
374   if (G_BYTES_IS_DATA (bytes))
375     {
376       GBytesData *data_bytes = (GBytesData *) bytes;
377
378       return data_bytes->data;
379     }
380   else if (G_BYTES_IS_INLINE (bytes))
381     {
382       GBytesInline *inline_bytes = (GBytesInline *) bytes;
383
384       return inline_bytes->data;
385     }
386   else
387     g_assert_not_reached ();
388 }
389
390 /**
391  * g_bytes_get_size:
392  * @bytes: a #GBytes
393  *
394  * Get the size of the byte data in the #GBytes.
395  *
396  * This function will always return the same value for a given #GBytes.
397  *
398  * Returns: the size
399  *
400  * Since: 2.32
401  */
402 gsize
403 g_bytes_get_size (GBytes *bytes)
404 {
405   g_return_val_if_fail (bytes != NULL, 0);
406   return bytes->size;
407 }
408
409 /**
410  * g_bytes_get_zero_copy_fd:
411  * @bytes: a #GBytes
412  *
413  * Gets the zero-copy fd from a #GBytes, if it has one.
414  *
415  * Returns -1 if @bytes was not created from a zero-copy fd.
416  *
417  * A #GBytes created with a zero-copy fd may have been internally
418  * converted into another type of #GBytes for any reason at all.  This
419  * function may therefore return -1 at any time, even for a #GBytes that
420  * was created with g_bytes_new_take_zero_copy_fd().
421  *
422  * The returned file descriptor belongs to @bytes.  Do not close it.
423  *
424  * Returns: a file descriptor, or -1
425  *
426  * Since: 2.44
427  */
428 gint
429 g_bytes_get_zero_copy_fd (GBytes *bytes)
430 {
431   g_return_val_if_fail (bytes != NULL, -1);
432
433   if (G_BYTES_IS_MEMFD (bytes))
434     return bytes->type_or_fd;
435   else
436     return -1;
437 }
438
439 /**
440  * g_bytes_ref:
441  * @bytes: a #GBytes
442  *
443  * Increase the reference count on @bytes.
444  *
445  * Returns: the #GBytes
446  *
447  * Since: 2.32
448  */
449 GBytes *
450 g_bytes_ref (GBytes *bytes)
451 {
452   g_return_val_if_fail (bytes != NULL, NULL);
453
454   g_atomic_int_inc (&bytes->ref_count);
455
456   return bytes;
457 }
458
459 /**
460  * g_bytes_unref:
461  * @bytes: (allow-none): a #GBytes
462  *
463  * Releases a reference on @bytes.  This may result in the bytes being
464  * freed.
465  *
466  * Since: 2.32
467  */
468 void
469 g_bytes_unref (GBytes *bytes)
470 {
471   if (bytes == NULL)
472     return;
473
474   if (g_atomic_int_dec_and_test (&bytes->ref_count))
475     {
476       switch (bytes->type_or_fd)
477         {
478         case G_BYTES_TYPE_STATIC:
479           /* data does not need to be freed */
480           g_slice_free (GBytesData, (GBytesData *) bytes);
481           break;
482
483         case G_BYTES_TYPE_INLINE:
484           /* data will be freed along with struct */
485           g_slice_free1 (G_STRUCT_OFFSET (GBytesInline, data[bytes->size]), bytes);
486           break;
487
488         case G_BYTES_TYPE_FREE:
489           {
490             GBytesData *data_bytes = (GBytesData *) bytes;
491
492             g_free (data_bytes->data);
493
494             g_slice_free (GBytesData, data_bytes);
495             break;
496           }
497
498         case G_BYTES_TYPE_NOTIFY:
499           {
500             GBytesNotify *notify_bytes = (GBytesNotify *) bytes;
501
502             /* We don't create GBytesNotify if callback was NULL */
503             (* notify_bytes->notify) (notify_bytes->user_data);
504
505             g_slice_free (GBytesNotify, notify_bytes);
506             break;
507           }
508
509         default:
510           {
511             GBytesData *data_bytes = (GBytesData *) bytes;
512
513             g_assert (bytes->type_or_fd >= 0);
514
515             g_assert_se (munmap (data_bytes->data, bytes->size) == 0);
516             g_assert_se (close (bytes->type_or_fd) == 0);
517
518             g_slice_free (GBytesData, data_bytes);
519             break;
520           }
521         }
522     }
523 }
524
525 /**
526  * g_bytes_equal:
527  * @bytes1: (type GLib.Bytes): a pointer to a #GBytes
528  * @bytes2: (type GLib.Bytes): a pointer to a #GBytes to compare with @bytes1
529  *
530  * Compares the two #GBytes values being pointed to and returns
531  * %TRUE if they are equal.
532  *
533  * This function can be passed to g_hash_table_new() as the @key_equal_func
534  * parameter, when using non-%NULL #GBytes pointers as keys in a #GHashTable.
535  *
536  * Returns: %TRUE if the two keys match.
537  *
538  * Since: 2.32
539  */
540 gboolean
541 g_bytes_equal (gconstpointer bytes1,
542                gconstpointer bytes2)
543 {
544   gconstpointer d1, d2;
545   gsize s1, s2;
546
547   g_return_val_if_fail (bytes1 != NULL, FALSE);
548   g_return_val_if_fail (bytes2 != NULL, FALSE);
549
550   d1 = g_bytes_get_data ((GBytes *) bytes1, &s1);
551   d2 = g_bytes_get_data ((GBytes *) bytes2, &s2);
552
553   if (s1 != s2)
554     return FALSE;
555
556   if (d1 == d2)
557     return TRUE;
558
559   return memcmp (d1, d2, s1) == 0;
560 }
561
562 /**
563  * g_bytes_hash:
564  * @bytes: (type GLib.Bytes): a pointer to a #GBytes key
565  *
566  * Creates an integer hash code for the byte data in the #GBytes.
567  *
568  * This function can be passed to g_hash_table_new() as the @key_hash_func
569  * parameter, when using non-%NULL #GBytes pointers as keys in a #GHashTable.
570  *
571  * Returns: a hash value corresponding to the key.
572  *
573  * Since: 2.32
574  */
575 guint
576 g_bytes_hash (gconstpointer bytes)
577 {
578   const guchar *data;
579   const guchar *end;
580   gsize size;
581   guint32 h = 5381;
582
583   g_return_val_if_fail (bytes != NULL, 0);
584
585   data = g_bytes_get_data ((GBytes *) bytes, &size);
586   end = data + size;
587
588   while (data != end)
589     h = (h << 5) + h + *(data++);
590
591   return h;
592 }
593
594 /**
595  * g_bytes_compare:
596  * @bytes1: (type GLib.Bytes): a pointer to a #GBytes
597  * @bytes2: (type GLib.Bytes): a pointer to a #GBytes to compare with @bytes1
598  *
599  * Compares the two #GBytes values.
600  *
601  * This function can be used to sort GBytes instances in lexographical order.
602  *
603  * Returns: a negative value if bytes2 is lesser, a positive value if bytes2 is
604  *          greater, and zero if bytes2 is equal to bytes1
605  *
606  * Since: 2.32
607  */
608 gint
609 g_bytes_compare (gconstpointer bytes1,
610                  gconstpointer bytes2)
611 {
612   gconstpointer d1, d2;
613   gsize s1, s2;
614   gint ret;
615
616   g_return_val_if_fail (bytes1 != NULL, 0);
617   g_return_val_if_fail (bytes2 != NULL, 0);
618
619   d1 = g_bytes_get_data ((GBytes *) bytes1, &s1);
620   d2 = g_bytes_get_data ((GBytes *) bytes2, &s2);
621
622   ret = memcmp (d1, d2, MIN (s1, s2));
623   if (ret == 0 && s1 != s2)
624     ret = s1 < s2 ? -1 : 1;
625
626   return ret;
627 }
628
629 /**
630  * g_bytes_unref_to_data:
631  * @bytes: (transfer full): a #GBytes
632  * @size: location to place the length of the returned data
633  *
634  * Unreferences the bytes, and returns a pointer the same byte data
635  * contents.
636  *
637  * As an optimization, the byte data is returned without copying if this was
638  * the last reference to bytes and bytes was created with g_bytes_new(),
639  * g_bytes_new_take() or g_byte_array_free_to_bytes(). In all other cases the
640  * data is copied.
641  *
642  * Returns: (transfer full): a pointer to the same byte data, which should
643  *          be freed with g_free()
644  *
645  * Since: 2.32
646  */
647 gpointer
648 g_bytes_unref_to_data (GBytes *bytes,
649                        gsize  *size)
650 {
651   gpointer result;
652
653   g_return_val_if_fail (bytes != NULL, NULL);
654   g_return_val_if_fail (size != NULL, NULL);
655
656
657   /*
658    * Optimal path: if this is was the last reference, then we can return
659    * the data from this GBytes without copying.
660    */
661   if (G_BYTES_IS_FREE(bytes) && g_atomic_int_get (&bytes->ref_count) == 1)
662     {
663       GBytesData *data_bytes = (GBytesData *) bytes;
664
665       result = data_bytes->data;
666       *size = bytes->size;
667
668       g_slice_free (GBytesData, data_bytes);
669     }
670   else
671     {
672       gconstpointer data;
673
674       data = g_bytes_get_data (bytes, size);
675       result = g_memdup (data, *size);
676       g_bytes_unref (bytes);
677     }
678
679   return result;
680 }
681
682 /**
683  * g_bytes_unref_to_array:
684  * @bytes: (transfer full): a #GBytes
685  *
686  * Unreferences the bytes, and returns a new mutable #GByteArray containing
687  * the same byte data.
688  *
689  * As an optimization, the byte data is transferred to the array without copying
690  * if this was the last reference to bytes and bytes was created with
691  * g_bytes_new(), g_bytes_new_take() or g_byte_array_free_to_bytes(). In all
692  * other cases the data is copied.
693  *
694  * Returns: (transfer full): a new mutable #GByteArray containing the same byte data
695  *
696  * Since: 2.32
697  */
698 GByteArray *
699 g_bytes_unref_to_array (GBytes *bytes)
700 {
701   gpointer data;
702   gsize size;
703
704   g_return_val_if_fail (bytes != NULL, NULL);
705
706   data = g_bytes_unref_to_data (bytes, &size);
707   return g_byte_array_new_take (data, size);
708 }