gbytes: Clarify the nullability of GBytes->data
[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, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Ryan Lortie <desrt@desrt.ca>
21  *         Stef Walter <stefw@collabora.co.uk>
22  */
23
24 #include "config.h"
25
26 #include "gbytes.h"
27
28 #include <glib/garray.h>
29 #include <glib/gstrfuncs.h>
30 #include <glib/gatomic.h>
31 #include <glib/gslice.h>
32 #include <glib/gtestutils.h>
33 #include <glib/gmem.h>
34 #include <glib/gmessages.h>
35
36 #include <string.h>
37
38 /**
39  * GBytes:
40  *
41  * A simple refcounted data type representing an immutable sequence of zero or
42  * more bytes from an unspecified origin.
43  *
44  * The purpose of a #GBytes is to keep the memory region that it holds
45  * alive for as long as anyone holds a reference to the bytes.  When
46  * the last reference count is dropped, the memory is released. Multiple
47  * unrelated callers can use byte data in the #GBytes without coordinating
48  * their activities, resting assured that the byte data will not change or
49  * move while they hold a reference.
50  *
51  * A #GBytes can come from many different origins that may have
52  * different procedures for freeing the memory region.  Examples are
53  * memory from g_malloc(), from memory slices, from a #GMappedFile or
54  * memory from other allocators.
55  *
56  * #GBytes work well as keys in #GHashTable. Use g_bytes_equal() and
57  * g_bytes_hash() as parameters to g_hash_table_new() or g_hash_table_new_full().
58  * #GBytes can also be used as keys in a #GTree by passing the g_bytes_compare()
59  * function to g_tree_new().
60  *
61  * The data pointed to by this bytes must not be modified. For a mutable
62  * array of bytes see #GByteArray. Use g_bytes_unref_to_array() to create a
63  * mutable array for a #GBytes sequence. To create an immutable #GBytes from
64  * a mutable #GByteArray, use the g_byte_array_free_to_bytes() function.
65  *
66  * Since: 2.32
67  **/
68
69 struct _GBytes
70 {
71   gconstpointer data;  /* may be NULL iff (size == 0) */
72   gsize size;  /* may be 0 */
73   gint ref_count;
74   GDestroyNotify free_func;
75   gpointer user_data;
76 };
77
78 /**
79  * g_bytes_new:
80  * @data: (transfer none) (array length=size) (element-type guint8) (allow-none):
81  *        the data to be used for the bytes
82  * @size: the size of @data
83  *
84  * Creates a new #GBytes from @data.
85  *
86  * @data is copied. If @size is 0, @data may be %NULL.
87  *
88  * Returns: (transfer full): a new #GBytes
89  *
90  * Since: 2.32
91  */
92 GBytes *
93 g_bytes_new (gconstpointer data,
94              gsize         size)
95 {
96   g_return_val_if_fail (data != NULL || size == 0, NULL);
97
98   return g_bytes_new_take (g_memdup (data, size), size);
99 }
100
101 /**
102  * g_bytes_new_take:
103  * @data: (transfer full) (array length=size) (element-type guint8) (allow-none):
104           the data to be used for the bytes
105  * @size: the size of @data
106  *
107  * Creates a new #GBytes from @data.
108  *
109  * After this call, @data belongs to the bytes and may no longer be
110  * modified by the caller.  g_free() will be called on @data when the
111  * bytes is no longer in use. Because of this @data must have been created by
112  * a call to g_malloc(), g_malloc0() or g_realloc() or by one of the many
113  * functions that wrap these calls (such as g_new(), g_strdup(), etc).
114  *
115  * For creating #GBytes with memory from other allocators, see
116  * g_bytes_new_with_free_func().
117  *
118  * @data may be %NULL if @size is 0.
119  *
120  * Returns: (transfer full): a new #GBytes
121  *
122  * Since: 2.32
123  */
124 GBytes *
125 g_bytes_new_take (gpointer data,
126                   gsize    size)
127 {
128   return g_bytes_new_with_free_func (data, size, g_free, data);
129 }
130
131
132 /**
133  * g_bytes_new_static: (skip)
134  * @data: (transfer full) (array length=size) (element-type guint8) (allow-none):
135           the data to be used for the bytes
136  * @size: the size of @data
137  *
138  * Creates a new #GBytes from static data.
139  *
140  * @data must be static (ie: never modified or freed). It may be %NULL if @size
141  * is 0.
142  *
143  * Returns: (transfer full): a new #GBytes
144  *
145  * Since: 2.32
146  */
147 GBytes *
148 g_bytes_new_static (gconstpointer data,
149                     gsize         size)
150 {
151   return g_bytes_new_with_free_func (data, size, NULL, NULL);
152 }
153
154 /**
155  * g_bytes_new_with_free_func:
156  * @data: (array length=size) (allow-none): the data to be used for the bytes
157  * @size: the size of @data
158  * @free_func: the function to call to release the data
159  * @user_data: data to pass to @free_func
160  *
161  * Creates a #GBytes from @data.
162  *
163  * When the last reference is dropped, @free_func will be called with the
164  * @user_data argument.
165  *
166  * @data must not be modified after this call is made until @free_func has
167  * been called to indicate that the bytes is no longer in use.
168  *
169  * @data may be %NULL if @size is 0.
170  *
171  * Returns: (transfer full): a new #GBytes
172  *
173  * Since: 2.32
174  */
175 GBytes *
176 g_bytes_new_with_free_func (gconstpointer  data,
177                             gsize          size,
178                             GDestroyNotify free_func,
179                             gpointer       user_data)
180 {
181   GBytes *bytes;
182
183   g_return_val_if_fail (data != NULL || size == 0, NULL);
184
185   bytes = g_slice_new (GBytes);
186   bytes->data = data;
187   bytes->size = size;
188   bytes->free_func = free_func;
189   bytes->user_data = user_data;
190   bytes->ref_count = 1;
191
192   return (GBytes *)bytes;
193 }
194
195 /**
196  * g_bytes_new_from_bytes:
197  * @bytes: a #GBytes
198  * @offset: offset which subsection starts at
199  * @length: length of subsection
200  *
201  * Creates a #GBytes which is a subsection of another #GBytes. The @offset +
202  * @length may not be longer than the size of @bytes.
203  *
204  * A reference to @bytes will be held by the newly created #GBytes until
205  * the byte data is no longer needed.
206  *
207  * Returns: (transfer full): a new #GBytes
208  *
209  * Since: 2.32
210  */
211 GBytes *
212 g_bytes_new_from_bytes (GBytes  *bytes,
213                         gsize    offset,
214                         gsize    length)
215 {
216   /* Note that length may be 0. */
217   g_return_val_if_fail (bytes != NULL, NULL);
218   g_return_val_if_fail (offset <= bytes->size, NULL);
219   g_return_val_if_fail (offset + length <= bytes->size, NULL);
220
221   return g_bytes_new_with_free_func ((gchar *)bytes->data + offset, length,
222                                      (GDestroyNotify)g_bytes_unref, g_bytes_ref (bytes));
223 }
224
225 /**
226  * g_bytes_get_data:
227  * @bytes: a #GBytes
228  * @size: (out) (allow-none): location to return size of byte data
229  *
230  * Get the byte data in the #GBytes. This data should not be modified.
231  *
232  * This function will always return the same pointer for a given #GBytes.
233  *
234  * %NULL may be returned if @size is 0. This is not guaranteed, as the #GBytes
235  * may represent an empty string with @data non-%NULL and @size as 0. %NULL will
236  * not be returned if @size is non-zero.
237  *
238  * Returns: (transfer none) (array length=size) (type guint8) (allow-none): a pointer to the
239  *          byte data, or %NULL
240  *
241  * Since: 2.32
242  */
243 gconstpointer
244 g_bytes_get_data (GBytes *bytes,
245                   gsize *size)
246 {
247   g_return_val_if_fail (bytes != NULL, NULL);
248   if (size)
249     *size = bytes->size;
250   return bytes->data;
251 }
252
253 /**
254  * g_bytes_get_size:
255  * @bytes: a #GBytes
256  *
257  * Get the size of the byte data in the #GBytes.
258  *
259  * This function will always return the same value for a given #GBytes.
260  *
261  * Returns: the size
262  *
263  * Since: 2.32
264  */
265 gsize
266 g_bytes_get_size (GBytes *bytes)
267 {
268   g_return_val_if_fail (bytes != NULL, 0);
269   return bytes->size;
270 }
271
272
273 /**
274  * g_bytes_ref:
275  * @bytes: a #GBytes
276  *
277  * Increase the reference count on @bytes.
278  *
279  * Returns: the #GBytes
280  *
281  * Since: 2.32
282  */
283 GBytes *
284 g_bytes_ref (GBytes *bytes)
285 {
286   g_return_val_if_fail (bytes != NULL, NULL);
287
288   g_atomic_int_inc (&bytes->ref_count);
289
290   return bytes;
291 }
292
293 /**
294  * g_bytes_unref:
295  * @bytes: (allow-none): a #GBytes
296  *
297  * Releases a reference on @bytes.  This may result in the bytes being
298  * freed.
299  *
300  * Since: 2.32
301  */
302 void
303 g_bytes_unref (GBytes *bytes)
304 {
305   if (bytes == NULL)
306     return;
307
308   if (g_atomic_int_dec_and_test (&bytes->ref_count))
309     {
310       if (bytes->free_func != NULL)
311         bytes->free_func (bytes->user_data);
312       g_slice_free (GBytes, bytes);
313     }
314 }
315
316 /**
317  * g_bytes_equal:
318  * @bytes1: (type GLib.Bytes): a pointer to a #GBytes
319  * @bytes2: (type GLib.Bytes): a pointer to a #GBytes to compare with @bytes1
320  *
321  * Compares the two #GBytes values being pointed to and returns
322  * %TRUE if they are equal.
323  *
324  * This function can be passed to g_hash_table_new() as the @key_equal_func
325  * parameter, when using non-%NULL #GBytes pointers as keys in a #GHashTable.
326  *
327  * Returns: %TRUE if the two keys match.
328  *
329  * Since: 2.32
330  */
331 gboolean
332 g_bytes_equal (gconstpointer bytes1,
333                gconstpointer bytes2)
334 {
335   const GBytes *b1 = bytes1;
336   const GBytes *b2 = bytes2;
337
338   g_return_val_if_fail (bytes1 != NULL, FALSE);
339   g_return_val_if_fail (bytes2 != NULL, FALSE);
340
341   return b1->size == b2->size &&
342          memcmp (b1->data, b2->data, b1->size) == 0;
343 }
344
345 /**
346  * g_bytes_hash:
347  * @bytes: (type GLib.Bytes): a pointer to a #GBytes key
348  *
349  * Creates an integer hash code for the byte data in the #GBytes.
350  *
351  * This function can be passed to g_hash_table_new() as the @key_equal_func
352  * parameter, when using non-%NULL #GBytes pointers as keys in a #GHashTable.
353  *
354  * Returns: a hash value corresponding to the key.
355  *
356  * Since: 2.32
357  */
358 guint
359 g_bytes_hash (gconstpointer bytes)
360 {
361   const GBytes *a = bytes;
362   const signed char *p, *e;
363   guint32 h = 5381;
364
365   g_return_val_if_fail (bytes != NULL, 0);
366
367   for (p = (signed char *)a->data, e = (signed char *)a->data + a->size; p != e; p++)
368     h = (h << 5) + h + *p;
369
370   return h;
371 }
372
373 /**
374  * g_bytes_compare:
375  * @bytes1: (type GLib.Bytes): a pointer to a #GBytes
376  * @bytes2: (type GLib.Bytes): a pointer to a #GBytes to compare with @bytes1
377  *
378  * Compares the two #GBytes values.
379  *
380  * This function can be used to sort GBytes instances in lexographical order.
381  *
382  * Returns: a negative value if bytes2 is lesser, a positive value if bytes2 is
383  *          greater, and zero if bytes2 is equal to bytes1
384  *
385  * Since: 2.32
386  */
387 gint
388 g_bytes_compare (gconstpointer bytes1,
389                  gconstpointer bytes2)
390 {
391   const GBytes *b1 = bytes1;
392   const GBytes *b2 = bytes2;
393   gint ret;
394
395   g_return_val_if_fail (bytes1 != NULL, 0);
396   g_return_val_if_fail (bytes2 != NULL, 0);
397
398   ret = memcmp (b1->data, b2->data, MIN (b1->size, b2->size));
399   if (ret == 0 && b1->size != b2->size)
400       ret = b1->size < b2->size ? -1 : 1;
401   return ret;
402 }
403
404 static gpointer
405 try_steal_and_unref (GBytes         *bytes,
406                      GDestroyNotify  free_func,
407                      gsize          *size)
408 {
409   gpointer result;
410
411   if (bytes->free_func != free_func || bytes->data == NULL)
412     return NULL;
413
414   /* Are we the only reference? */
415   if (g_atomic_int_get (&bytes->ref_count) == 1)
416     {
417       *size = bytes->size;
418       result = (gpointer)bytes->data;
419       g_slice_free (GBytes, bytes);
420       return result;
421     }
422
423   return NULL;
424 }
425
426
427 /**
428  * g_bytes_unref_to_data:
429  * @bytes: (transfer full): a #GBytes
430  * @size: location to place the length of the returned data
431  *
432  * Unreferences the bytes, and returns a pointer the same byte data
433  * contents.
434  *
435  * As an optimization, the byte data is returned without copying if this was
436  * the last reference to bytes and bytes was created with g_bytes_new(),
437  * g_bytes_new_take() or g_byte_array_free_to_bytes(). In all other cases the
438  * data is copied.
439  *
440  * Returns: (transfer full): a pointer to the same byte data, which should
441  *          be freed with g_free()
442  *
443  * Since: 2.32
444  */
445 gpointer
446 g_bytes_unref_to_data (GBytes *bytes,
447                        gsize  *size)
448 {
449   gpointer result;
450
451   g_return_val_if_fail (bytes != NULL, NULL);
452   g_return_val_if_fail (size != NULL, NULL);
453
454   /*
455    * Optimal path: if this is was the last reference, then we can return
456    * the data from this GBytes without copying.
457    */
458
459   result = try_steal_and_unref (bytes, g_free, size);
460   if (result == NULL)
461     {
462       /*
463        * Copy: Non g_malloc (or compatible) allocator, or static memory,
464        * so we have to copy, and then unref.
465        */
466       result = g_memdup (bytes->data, bytes->size);
467       *size = bytes->size;
468       g_bytes_unref (bytes);
469     }
470
471   return result;
472 }
473
474 /**
475  * g_bytes_unref_to_array:
476  * @bytes: (transfer full): a #GBytes
477  *
478  * Unreferences the bytes, and returns a new mutable #GByteArray containing
479  * the same byte data.
480  *
481  * As an optimization, the byte data is transferred to the array without copying
482  * if this was the last reference to bytes and bytes was created with
483  * g_bytes_new(), g_bytes_new_take() or g_byte_array_free_to_bytes(). In all
484  * other cases the data is copied.
485  *
486  * Returns: (transfer full): a new mutable #GByteArray containing the same byte data
487  *
488  * Since: 2.32
489  */
490 GByteArray *
491 g_bytes_unref_to_array (GBytes *bytes)
492 {
493   gpointer data;
494   gsize size;
495
496   g_return_val_if_fail (bytes != NULL, NULL);
497
498   data = g_bytes_unref_to_data (bytes, &size);
499   return g_byte_array_new_take (data, size);
500 }