GArray, GPtrArray: factor out the actual freeing
[platform/upstream/glib.git] / glib / garray.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /* 
28  * MT safe
29  */
30
31 #include "config.h"
32
33 #include <string.h>
34 #include <stdlib.h>
35
36 #include "garray.h"
37
38 #include "gbytes.h"
39 #include "gslice.h"
40 #include "gmem.h"
41 #include "gtestutils.h"
42 #include "gthread.h"
43 #include "gmessages.h"
44 #include "gqsort.h"
45
46
47 /**
48  * SECTION:arrays
49  * @title: Arrays
50  * @short_description: arrays of arbitrary elements which grow
51  *                     automatically as elements are added
52  *
53  * Arrays are similar to standard C arrays, except that they grow
54  * automatically as elements are added.
55  *
56  * Array elements can be of any size (though all elements of one array
57  * are the same size), and the array can be automatically cleared to
58  * '0's and zero-terminated.
59  *
60  * To create a new array use g_array_new().
61  *
62  * To add elements to an array, use g_array_append_val(),
63  * g_array_append_vals(), g_array_prepend_val(), and
64  * g_array_prepend_vals().
65  *
66  * To access an element of an array, use g_array_index().
67  *
68  * To set the size of an array, use g_array_set_size().
69  *
70  * To free an array, use g_array_free().
71  *
72  * <example>
73  *  <title>Using a #GArray to store #gint values</title>
74  *  <programlisting>
75  *   GArray *garray;
76  *   gint i;
77  *   /<!-- -->* We create a new array to store gint values.
78  *      We don't want it zero-terminated or cleared to 0's. *<!-- -->/
79  *   garray = g_array_new (FALSE, FALSE, sizeof (gint));
80  *   for (i = 0; i &lt; 10000; i++)
81  *     g_array_append_val (garray, i);
82  *   for (i = 0; i &lt; 10000; i++)
83  *     if (g_array_index (garray, gint, i) != i)
84  *       g_print ("ERROR: got &percnt;d instead of &percnt;d\n",
85  *                g_array_index (garray, gint, i), i);
86  *   g_array_free (garray, TRUE);
87  *  </programlisting>
88  * </example>
89  **/
90
91 #define MIN_ARRAY_SIZE  16
92
93 typedef struct _GRealArray  GRealArray;
94
95 /**
96  * GArray:
97  * @data: a pointer to the element data. The data may be moved as
98  *        elements are added to the #GArray.
99  * @len: the number of elements in the #GArray not including the
100  *       possible terminating zero element.
101  *
102  * Contains the public fields of an <link linkend="glib-Arrays">Array</link>.
103  **/
104 struct _GRealArray
105 {
106   guint8 *data;
107   guint   len;
108   guint   alloc;
109   guint   elt_size;
110   guint   zero_terminated : 1;
111   guint   clear : 1;
112   gint    ref_count;
113 };
114
115 /**
116  * g_array_index:
117  * @a: a #GArray.
118  * @t: the type of the elements.
119  * @i: the index of the element to return.
120  * @Returns: the element of the #GArray at the index given by @i.
121  *
122  * Returns the element of a #GArray at the given index. The return
123  * value is cast to the given type.
124  *
125  * <example>
126  *  <title>Getting a pointer to an element in a #GArray</title>
127  *  <programlisting>
128  *   EDayViewEvent *event;
129  *   /<!-- -->* This gets a pointer to the 4th element
130  *      in the array of EDayViewEvent structs. *<!-- -->/
131  *   event = &amp;g_array_index (events, EDayViewEvent, 3);
132  *  </programlisting>
133  * </example>
134  **/
135
136 #define g_array_elt_len(array,i) ((array)->elt_size * (i))
137 #define g_array_elt_pos(array,i) ((array)->data + g_array_elt_len((array),(i)))
138 #define g_array_elt_zero(array, pos, len)                               \
139   (memset (g_array_elt_pos ((array), pos), 0,  g_array_elt_len ((array), len)))
140 #define g_array_zero_terminate(array) G_STMT_START{                     \
141   if ((array)->zero_terminated)                                         \
142     g_array_elt_zero ((array), (array)->len, 1);                        \
143 }G_STMT_END
144
145 static guint g_nearest_pow        (gint        num) G_GNUC_CONST;
146 static void  g_array_maybe_expand (GRealArray *array,
147                                    gint        len);
148
149 /**
150  * g_array_new:
151  * @zero_terminated: %TRUE if the array should have an extra element at
152  *                   the end which is set to 0.
153  * @clear_: %TRUE if #GArray elements should be automatically cleared
154  *          to 0 when they are allocated.
155  * @element_size: the size of each element in bytes.
156  * @Returns: the new #GArray.
157  *
158  * Creates a new #GArray with a reference count of 1.
159  **/
160 GArray*
161 g_array_new (gboolean zero_terminated,
162              gboolean clear,
163              guint    elt_size)
164 {
165   return (GArray*) g_array_sized_new (zero_terminated, clear, elt_size, 0);
166 }
167
168 /**
169  * g_array_sized_new:
170  * @zero_terminated: %TRUE if the array should have an extra element at
171  *                   the end with all bits cleared.
172  * @clear_: %TRUE if all bits in the array should be cleared to 0 on
173  *          allocation.
174  * @element_size: size of each element in the array.
175  * @reserved_size: number of elements preallocated.
176  * @Returns: the new #GArray.
177  *
178  * Creates a new #GArray with @reserved_size elements preallocated and
179  * a reference count of 1. This avoids frequent reallocation, if you
180  * are going to add many elements to the array. Note however that the
181  * size of the array is still 0.
182  **/
183 GArray* g_array_sized_new (gboolean zero_terminated,
184                            gboolean clear,
185                            guint    elt_size,
186                            guint    reserved_size)
187 {
188   GRealArray *array = g_slice_new (GRealArray);
189
190   array->data            = NULL;
191   array->len             = 0;
192   array->alloc           = 0;
193   array->zero_terminated = (zero_terminated ? 1 : 0);
194   array->clear           = (clear ? 1 : 0);
195   array->elt_size        = elt_size;
196   array->ref_count       = 1;
197
198   if (array->zero_terminated || reserved_size != 0)
199     {
200       g_array_maybe_expand (array, reserved_size);
201       g_array_zero_terminate(array);
202     }
203
204   return (GArray*) array;
205 }
206
207 /**
208  * g_array_ref:
209  * @array: A #GArray.
210  *
211  * Atomically increments the reference count of @array by one. This
212  * function is MT-safe and may be called from any thread.
213  *
214  * Returns: The passed in #GArray.
215  *
216  * Since: 2.22
217  **/
218 GArray *
219 g_array_ref (GArray *array)
220 {
221   GRealArray *rarray = (GRealArray*) array;
222   g_return_val_if_fail (array, NULL);
223
224   g_atomic_int_inc (&rarray->ref_count);
225
226   return array;
227 }
228
229 typedef enum
230 {
231   FREE_SEGMENT = 1 << 0,
232   PRESERVE_WRAPPER = 1 << 1
233 } ArrayFreeFlags;
234
235 static gchar *array_free (GRealArray *, ArrayFreeFlags);
236
237 /**
238  * g_array_unref:
239  * @array: A #GArray.
240  *
241  * Atomically decrements the reference count of @array by one. If the
242  * reference count drops to 0, all memory allocated by the array is
243  * released. This function is MT-safe and may be called from any
244  * thread.
245  *
246  * Since: 2.22
247  **/
248 void
249 g_array_unref (GArray *array)
250 {
251   GRealArray *rarray = (GRealArray*) array;
252   g_return_if_fail (array);
253
254   if (g_atomic_int_dec_and_test (&rarray->ref_count))
255     array_free (rarray, FREE_SEGMENT);
256 }
257
258 /**
259  * g_array_get_element_size:
260  * @array: A #GArray.
261  *
262  * Gets the size of the elements in @array.
263  *
264  * Returns: Size of each element, in bytes.
265  *
266  * Since: 2.22
267  **/
268 guint
269 g_array_get_element_size (GArray *array)
270 {
271   GRealArray *rarray = (GRealArray*) array;
272
273   g_return_val_if_fail (array, 0);
274
275   return rarray->elt_size;
276 }
277
278 /**
279  * g_array_free:
280  * @array: a #GArray.
281  * @free_segment: if %TRUE the actual element data is freed as well.
282  * @Returns: the element data if @free_segment is %FALSE, otherwise
283  *           %NULL.  The element data should be freed using g_free().
284  *
285  * Frees the memory allocated for the #GArray. If @free_segment is
286  * %TRUE it frees the memory block holding the elements as well and
287  * also each element if @array has a @element_free_func set. Pass
288  * %FALSE if you want to free the #GArray wrapper but preserve the
289  * underlying array for use elsewhere. If the reference count of @array
290  * is greater than one, the #GArray wrapper is preserved but the size
291  * of @array will be set to zero.
292  *
293  * <note><para>If array elements contain dynamically-allocated memory,
294  * they should be freed separately.</para></note>
295  **/
296 gchar*
297 g_array_free (GArray   *farray,
298               gboolean  free_segment)
299 {
300   GRealArray *array = (GRealArray*) farray;
301   ArrayFreeFlags flags;
302
303   g_return_val_if_fail (array, NULL);
304
305   flags = (free_segment ? FREE_SEGMENT : 0);
306
307   /* if others are holding a reference, preserve the wrapper but do free/return the data */
308   if (g_atomic_int_get (&array->ref_count) > 1)
309     flags |= PRESERVE_WRAPPER;
310
311   return array_free (array, flags);
312 }
313
314 static gchar *
315 array_free (GRealArray     *array,
316             ArrayFreeFlags  flags)
317 {
318   gchar *segment;
319
320   if (flags & FREE_SEGMENT)
321     {
322       g_free (array->data);
323       segment = NULL;
324     }
325   else
326     segment = (gchar*) array->data;
327
328   if (flags & PRESERVE_WRAPPER)
329     {
330       array->data            = NULL;
331       array->len             = 0;
332       array->alloc           = 0;
333     }
334   else
335     {
336       g_slice_free1 (sizeof (GRealArray), array);
337     }
338
339   return segment;
340 }
341
342 /**
343  * g_array_append_vals:
344  * @array: a #GArray.
345  * @data: a pointer to the elements to append to the end of the array.
346  * @len: the number of elements to append.
347  * @Returns: the #GArray.
348  *
349  * Adds @len elements onto the end of the array.
350  **/
351 /**
352  * g_array_append_val:
353  * @a: a #GArray.
354  * @v: the value to append to the #GArray.
355  * @Returns: the #GArray.
356  *
357  * Adds the value on to the end of the array. The array will grow in
358  * size automatically if necessary.
359  *
360  * <note><para>g_array_append_val() is a macro which uses a reference
361  * to the value parameter @v. This means that you cannot use it with
362  * literal values such as "27". You must use variables.</para></note>
363  **/
364 GArray*
365 g_array_append_vals (GArray       *farray,
366                      gconstpointer data,
367                      guint         len)
368 {
369   GRealArray *array = (GRealArray*) farray;
370
371   g_return_val_if_fail (array, NULL);
372
373   g_array_maybe_expand (array, len);
374
375   memcpy (g_array_elt_pos (array, array->len), data, 
376           g_array_elt_len (array, len));
377
378   array->len += len;
379
380   g_array_zero_terminate (array);
381
382   return farray;
383 }
384
385 /**
386  * g_array_prepend_vals:
387  * @array: a #GArray.
388  * @data: a pointer to the elements to prepend to the start of the
389  *        array.
390  * @len: the number of elements to prepend.
391  * @Returns: the #GArray.
392  *
393  * Adds @len elements onto the start of the array.
394  *
395  * This operation is slower than g_array_append_vals() since the
396  * existing elements in the array have to be moved to make space for
397  * the new elements.
398  **/
399 /**
400  * g_array_prepend_val:
401  * @a: a #GArray.
402  * @v: the value to prepend to the #GArray.
403  * @Returns: the #GArray.
404  *
405  * Adds the value on to the start of the array. The array will grow in
406  * size automatically if necessary.
407  *
408  * This operation is slower than g_array_append_val() since the
409  * existing elements in the array have to be moved to make space for
410  * the new element.
411  *
412  * <note><para>g_array_prepend_val() is a macro which uses a reference
413  * to the value parameter @v. This means that you cannot use it with
414  * literal values such as "27". You must use variables.</para></note>
415  **/
416 GArray*
417 g_array_prepend_vals (GArray        *farray,
418                       gconstpointer  data,
419                       guint          len)
420 {
421   GRealArray *array = (GRealArray*) farray;
422
423   g_return_val_if_fail (array, NULL);
424
425   g_array_maybe_expand (array, len);
426
427   g_memmove (g_array_elt_pos (array, len), g_array_elt_pos (array, 0), 
428              g_array_elt_len (array, array->len));
429
430   memcpy (g_array_elt_pos (array, 0), data, g_array_elt_len (array, len));
431
432   array->len += len;
433
434   g_array_zero_terminate (array);
435
436   return farray;
437 }
438
439 /**
440  * g_array_insert_vals:
441  * @array: a #GArray.
442  * @index_: the index to place the elements at.
443  * @data: a pointer to the elements to insert.
444  * @len: the number of elements to insert.
445  * @Returns: the #GArray.
446  *
447  * Inserts @len elements into a #GArray at the given index.
448  **/
449 /**
450  * g_array_insert_val:
451  * @a: a #GArray.
452  * @i: the index to place the element at.
453  * @v: the value to insert into the array.
454  * @Returns: the #GArray.
455  *
456  * Inserts an element into an array at the given index.
457  *
458  * <note><para>g_array_insert_val() is a macro which uses a reference
459  * to the value parameter @v. This means that you cannot use it with
460  * literal values such as "27". You must use variables.</para></note>
461  **/
462 GArray*
463 g_array_insert_vals (GArray        *farray,
464                      guint          index_,
465                      gconstpointer  data,
466                      guint          len)
467 {
468   GRealArray *array = (GRealArray*) farray;
469
470   g_return_val_if_fail (array, NULL);
471
472   g_array_maybe_expand (array, len);
473
474   g_memmove (g_array_elt_pos (array, len + index_), 
475              g_array_elt_pos (array, index_), 
476              g_array_elt_len (array, array->len - index_));
477
478   memcpy (g_array_elt_pos (array, index_), data, g_array_elt_len (array, len));
479
480   array->len += len;
481
482   g_array_zero_terminate (array);
483
484   return farray;
485 }
486
487 /**
488  * g_array_set_size:
489  * @array: a #GArray.
490  * @length: the new size of the #GArray.
491  * @Returns: the #GArray.
492  *
493  * Sets the size of the array, expanding it if necessary. If the array
494  * was created with @clear_ set to %TRUE, the new elements are set to 0.
495  **/
496 GArray*
497 g_array_set_size (GArray *farray,
498                   guint   length)
499 {
500   GRealArray *array = (GRealArray*) farray;
501
502   g_return_val_if_fail (array, NULL);
503
504   if (length > array->len)
505     {
506       g_array_maybe_expand (array, length - array->len);
507       
508       if (array->clear)
509         g_array_elt_zero (array, array->len, length - array->len);
510     }
511   else if (G_UNLIKELY (g_mem_gc_friendly) && length < array->len)
512     g_array_elt_zero (array, length, array->len - length);
513   
514   array->len = length;
515   
516   g_array_zero_terminate (array);
517   
518   return farray;
519 }
520
521 /**
522  * g_array_remove_index:
523  * @array: a #GArray.
524  * @index_: the index of the element to remove.
525  * @Returns: the #GArray.
526  *
527  * Removes the element at the given index from a #GArray. The following
528  * elements are moved down one place.
529  **/
530 GArray*
531 g_array_remove_index (GArray *farray,
532                       guint   index_)
533 {
534   GRealArray* array = (GRealArray*) farray;
535
536   g_return_val_if_fail (array, NULL);
537
538   g_return_val_if_fail (index_ < array->len, NULL);
539
540   if (index_ != array->len - 1)
541     g_memmove (g_array_elt_pos (array, index_),
542                g_array_elt_pos (array, index_ + 1),
543                g_array_elt_len (array, array->len - index_ - 1));
544   
545   array->len -= 1;
546
547   if (G_UNLIKELY (g_mem_gc_friendly))
548     g_array_elt_zero (array, array->len, 1);
549   else
550     g_array_zero_terminate (array);
551
552   return farray;
553 }
554
555 /**
556  * g_array_remove_index_fast:
557  * @array: a @GArray.
558  * @index_: the index of the element to remove.
559  * @Returns: the #GArray.
560  *
561  * Removes the element at the given index from a #GArray. The last
562  * element in the array is used to fill in the space, so this function
563  * does not preserve the order of the #GArray. But it is faster than
564  * g_array_remove_index().
565  **/
566 GArray*
567 g_array_remove_index_fast (GArray *farray,
568                            guint   index_)
569 {
570   GRealArray* array = (GRealArray*) farray;
571
572   g_return_val_if_fail (array, NULL);
573
574   g_return_val_if_fail (index_ < array->len, NULL);
575
576   if (index_ != array->len - 1)
577     memcpy (g_array_elt_pos (array, index_), 
578             g_array_elt_pos (array, array->len - 1),
579             g_array_elt_len (array, 1));
580   
581   array->len -= 1;
582
583   if (G_UNLIKELY (g_mem_gc_friendly))
584     g_array_elt_zero (array, array->len, 1);
585   else
586     g_array_zero_terminate (array);
587
588   return farray;
589 }
590
591 /**
592  * g_array_remove_range:
593  * @array: a @GArray.
594  * @index_: the index of the first element to remove.
595  * @length: the number of elements to remove.
596  * @Returns: the #GArray.
597  *
598  * Removes the given number of elements starting at the given index
599  * from a #GArray.  The following elements are moved to close the gap.
600  *
601  * Since: 2.4
602  **/
603 GArray*
604 g_array_remove_range (GArray *farray,
605                       guint   index_,
606                       guint   length)
607 {
608   GRealArray *array = (GRealArray*) farray;
609
610   g_return_val_if_fail (array, NULL);
611   g_return_val_if_fail (index_ < array->len, NULL);
612   g_return_val_if_fail (index_ + length <= array->len, NULL);
613
614   if (index_ + length != array->len)
615     g_memmove (g_array_elt_pos (array, index_), 
616                g_array_elt_pos (array, index_ + length), 
617                (array->len - (index_ + length)) * array->elt_size);
618
619   array->len -= length;
620   if (G_UNLIKELY (g_mem_gc_friendly))
621     g_array_elt_zero (array, array->len, length);
622   else
623     g_array_zero_terminate (array);
624
625   return farray;
626 }
627
628 /**
629  * g_array_sort:
630  * @array: a #GArray.
631  * @compare_func: comparison function.
632  *
633  * Sorts a #GArray using @compare_func which should be a qsort()-style
634  * comparison function (returns less than zero for first arg is less
635  * than second arg, zero for equal, greater zero if first arg is
636  * greater than second arg).
637  *
638  * If two array elements compare equal, their order in the sorted array
639  * is undefined. If you want equal elements to keep their order (i.e.
640  * you want a stable sort) you can write a comparison function that,
641  * if two elements would otherwise compare equal, compares them by
642  * their addresses.
643  **/
644 void
645 g_array_sort (GArray       *farray,
646               GCompareFunc  compare_func)
647 {
648   GRealArray *array = (GRealArray*) farray;
649
650   g_return_if_fail (array != NULL);
651
652   qsort (array->data,
653          array->len,
654          array->elt_size,
655          compare_func);
656 }
657
658 /**
659  * g_array_sort_with_data:
660  * @array: a #GArray.
661  * @compare_func: comparison function.
662  * @user_data: data to pass to @compare_func.
663  *
664  * Like g_array_sort(), but the comparison function receives an extra
665  * user data argument.
666  **/
667 void
668 g_array_sort_with_data (GArray           *farray,
669                         GCompareDataFunc  compare_func,
670                         gpointer          user_data)
671 {
672   GRealArray *array = (GRealArray*) farray;
673
674   g_return_if_fail (array != NULL);
675
676   g_qsort_with_data (array->data,
677                      array->len,
678                      array->elt_size,
679                      compare_func,
680                      user_data);
681 }
682
683 /* Returns the smallest power of 2 greater than n, or n if
684  * such power does not fit in a guint
685  */
686 static guint
687 g_nearest_pow (gint num)
688 {
689   guint n = 1;
690
691   while (n < num && n > 0)
692     n <<= 1;
693
694   return n ? n : num;
695 }
696
697 static void
698 g_array_maybe_expand (GRealArray *array,
699                       gint        len)
700 {
701   guint want_alloc = g_array_elt_len (array, array->len + len + 
702                                       array->zero_terminated);
703
704   if (want_alloc > array->alloc)
705     {
706       want_alloc = g_nearest_pow (want_alloc);
707       want_alloc = MAX (want_alloc, MIN_ARRAY_SIZE);
708
709       array->data = g_realloc (array->data, want_alloc);
710
711       if (G_UNLIKELY (g_mem_gc_friendly))
712         memset (array->data + array->alloc, 0, want_alloc - array->alloc);
713
714       array->alloc = want_alloc;
715     }
716 }
717
718 /**
719  * SECTION:arrays_pointer
720  * @title: Pointer Arrays
721  * @short_description: arrays of pointers to any type of data, which
722  *                     grow automatically as new elements are added
723  *
724  * Pointer Arrays are similar to Arrays but are used only for storing
725  * pointers.
726  *
727  * <note><para>If you remove elements from the array, elements at the
728  * end of the array are moved into the space previously occupied by the
729  * removed element. This means that you should not rely on the index of
730  * particular elements remaining the same. You should also be careful
731  * when deleting elements while iterating over the array.</para></note>
732  *
733  * To create a pointer array, use g_ptr_array_new().
734  *
735  * To add elements to a pointer array, use g_ptr_array_add().
736  *
737  * To remove elements from a pointer array, use g_ptr_array_remove(),
738  * g_ptr_array_remove_index() or g_ptr_array_remove_index_fast().
739  *
740  * To access an element of a pointer array, use g_ptr_array_index().
741  *
742  * To set the size of a pointer array, use g_ptr_array_set_size().
743  *
744  * To free a pointer array, use g_ptr_array_free().
745  *
746  * <example>
747  *  <title>Using a #GPtrArray</title>
748  *  <programlisting>
749  *   GPtrArray *gparray;
750  *   gchar *string1 = "one", *string2 = "two", *string3 = "three";
751  *
752  *   gparray = g_ptr_array_new (<!-- -->);
753  *   g_ptr_array_add (gparray, (gpointer) string1);
754  *   g_ptr_array_add (gparray, (gpointer) string2);
755  *   g_ptr_array_add (gparray, (gpointer) string3);
756  *
757  *   if (g_ptr_array_index (gparray, 0) != (gpointer) string1)
758  *     g_print ("ERROR: got &percnt;p instead of &percnt;p\n",
759  *              g_ptr_array_index (gparray, 0), string1);
760  *
761  *   g_ptr_array_free (gparray, TRUE);
762  *  </programlisting>
763  * </example>
764  **/
765
766 typedef struct _GRealPtrArray  GRealPtrArray;
767
768 /**
769  * GPtrArray:
770  * @pdata: points to the array of pointers, which may be moved when the
771  *         array grows.
772  * @len: number of pointers in the array.
773  *
774  * Contains the public fields of a pointer array.
775  **/
776 struct _GRealPtrArray
777 {
778   gpointer     *pdata;
779   guint         len;
780   guint         alloc;
781   gint          ref_count;
782   GDestroyNotify element_free_func;
783 };
784
785 /**
786  * g_ptr_array_index:
787  * @array: a #GPtrArray.
788  * @index_: the index of the pointer to return.
789  * @Returns: the pointer at the given index.
790  *
791  * Returns the pointer at the given index of the pointer array.
792  **/
793
794 static void g_ptr_array_maybe_expand (GRealPtrArray *array,
795                                       gint           len);
796
797 /**
798  * g_ptr_array_new:
799  * @Returns: the new #GPtrArray.
800  *
801  * Creates a new #GPtrArray with a reference count of 1.
802  **/
803 GPtrArray*
804 g_ptr_array_new (void)
805 {
806   return g_ptr_array_sized_new (0);
807 }
808
809 /**
810  * g_ptr_array_sized_new:
811  * @reserved_size: number of pointers preallocated.
812  * @Returns: the new #GPtrArray.
813  *
814  * Creates a new #GPtrArray with @reserved_size pointers preallocated
815  * and a reference count of 1. This avoids frequent reallocation, if
816  * you are going to add many pointers to the array. Note however that
817  * the size of the array is still 0.
818  **/
819 GPtrArray*  
820 g_ptr_array_sized_new (guint reserved_size)
821 {
822   GRealPtrArray *array = g_slice_new (GRealPtrArray);
823
824   array->pdata = NULL;
825   array->len = 0;
826   array->alloc = 0;
827   array->ref_count = 1;
828   array->element_free_func = NULL;
829
830   if (reserved_size != 0)
831     g_ptr_array_maybe_expand (array, reserved_size);
832
833   return (GPtrArray*) array;  
834 }
835
836 /**
837  * g_ptr_array_new_with_free_func:
838  * @element_free_func: A function to free elements with destroy @array or %NULL.
839  *
840  * Creates a new #GPtrArray with a reference count of 1 and use @element_free_func
841  * for freeing each element when the array is destroyed either via
842  * g_ptr_array_unref(), when g_ptr_array_free() is called with @free_segment
843  * set to %TRUE or when removing elements.
844  *
845  * Returns: A new #GPtrArray.
846  *
847  * Since: 2.22
848  **/
849 GPtrArray *
850 g_ptr_array_new_with_free_func (GDestroyNotify element_free_func)
851 {
852   GPtrArray *array;
853
854   array = g_ptr_array_new ();
855   g_ptr_array_set_free_func (array, element_free_func);
856   return array;
857 }
858
859 /**
860  * g_ptr_array_new_full:
861  * @reserved_size: number of pointers preallocated.
862  * @element_free_func: A function to free elements with destroy @array or %NULL.
863  *
864  * Creates a new #GPtrArray with @reserved_size pointers preallocated
865  * and a reference count of 1. This avoids frequent reallocation, if
866  * you are going to add many pointers to the array. Note however that
867  * the size of the array is still 0. It also set @element_free_func
868  * for freeing each element when the array is destroyed either via
869  * g_ptr_array_unref(), when g_ptr_array_free() is called with @free_segment
870  * set to %TRUE or when removing elements.
871  *
872  * Returns: A new #GPtrArray.
873  *
874  * Since: 2.30
875  **/
876 GPtrArray *
877 g_ptr_array_new_full (guint          reserved_size,
878                       GDestroyNotify element_free_func)
879 {
880   GPtrArray *array;
881
882   array = g_ptr_array_sized_new (reserved_size);
883   g_ptr_array_set_free_func (array, element_free_func);
884   return array;
885 }
886
887 /**
888  * g_ptr_array_set_free_func:
889  * @array: A #GPtrArray.
890  * @element_free_func: A function to free elements with destroy @array or %NULL.
891  *
892  * Sets a function for freeing each element when @array is destroyed
893  * either via g_ptr_array_unref(), when g_ptr_array_free() is called
894  * with @free_segment set to %TRUE or when removing elements.
895  *
896  * Since: 2.22
897  **/
898 void
899 g_ptr_array_set_free_func (GPtrArray        *array,
900                            GDestroyNotify    element_free_func)
901 {
902   GRealPtrArray* rarray = (GRealPtrArray*) array;
903
904   g_return_if_fail (array);
905
906   rarray->element_free_func = element_free_func;
907 }
908
909 /**
910  * g_ptr_array_ref:
911  * @array: A #GArray.
912  *
913  * Atomically increments the reference count of @array by one. This
914  * function is MT-safe and may be called from any thread.
915  *
916  * Returns: The passed in #GPtrArray.
917  *
918  * Since: 2.22
919  **/
920 GPtrArray *
921 g_ptr_array_ref (GPtrArray *array)
922 {
923   GRealPtrArray *rarray = (GRealPtrArray*) array;
924
925   g_return_val_if_fail (array, NULL);
926
927   g_atomic_int_inc (&rarray->ref_count);
928
929   return array;
930 }
931
932 static gpointer *ptr_array_free (GPtrArray *, ArrayFreeFlags);
933
934 /**
935  * g_ptr_array_unref:
936  * @array: A #GPtrArray.
937  *
938  * Atomically decrements the reference count of @array by one. If the
939  * reference count drops to 0, the effect is the same as calling
940  * g_ptr_array_free() with @free_segment set to %TRUE. This function
941  * is MT-safe and may be called from any thread.
942  *
943  * Since: 2.22
944  **/
945 void
946 g_ptr_array_unref (GPtrArray *array)
947 {
948   GRealPtrArray *rarray = (GRealPtrArray*) array;
949   g_return_if_fail (array);
950
951   if (g_atomic_int_dec_and_test (&rarray->ref_count))
952     ptr_array_free (array, FREE_SEGMENT);
953 }
954
955 /**
956  * g_ptr_array_free:
957  * @array: a #GPtrArray.
958  * @free_seg: if %TRUE the actual pointer array is freed as well.
959  * @Returns: the pointer array if @free_seg is %FALSE, otherwise %NULL.
960  *           The pointer array should be freed using g_free().
961  *
962  * Frees the memory allocated for the #GPtrArray. If @free_seg is %TRUE
963  * it frees the memory block holding the elements as well. Pass %FALSE
964  * if you want to free the #GPtrArray wrapper but preserve the
965  * underlying array for use elsewhere. If the reference count of @array
966  * is greater than one, the #GPtrArray wrapper is preserved but the
967  * size of @array will be set to zero.
968  *
969  * <note><para>If array contents point to dynamically-allocated
970  * memory, they should be freed separately if @free_seg is %TRUE and no
971  * #GDestroyNotify function has been set for @array.</para></note>
972  **/
973 gpointer*
974 g_ptr_array_free (GPtrArray *farray,
975                   gboolean   free_segment)
976 {
977   GRealPtrArray *array = (GRealPtrArray*) farray;
978   ArrayFreeFlags flags;
979
980   g_return_val_if_fail (array, NULL);
981
982   flags = (free_segment ? FREE_SEGMENT : 0);
983
984   /* if others are holding a reference, preserve the wrapper but do free/return the data */
985   if (g_atomic_int_get (&array->ref_count) > 1)
986     flags |= PRESERVE_WRAPPER;
987
988   return ptr_array_free (farray, flags);
989 }
990
991 static gpointer *
992 ptr_array_free (GPtrArray      *farray,
993                 ArrayFreeFlags  flags)
994 {
995   GRealPtrArray *array = (GRealPtrArray*) farray;
996   gpointer *segment;
997
998   if (flags & FREE_SEGMENT)
999     {
1000       if (array->element_free_func != NULL)
1001         g_ptr_array_foreach (farray, (GFunc) array->element_free_func, NULL);
1002       g_free (array->pdata);
1003       segment = NULL;
1004     }
1005   else
1006     segment = array->pdata;
1007
1008   if (flags & PRESERVE_WRAPPER)
1009     {
1010       array->pdata = NULL;
1011       array->len = 0;
1012       array->alloc = 0;
1013     }
1014   else
1015     {
1016       g_slice_free1 (sizeof (GRealPtrArray), array);
1017     }
1018
1019   return segment;
1020 }
1021
1022 static void
1023 g_ptr_array_maybe_expand (GRealPtrArray *array,
1024                           gint           len)
1025 {
1026   if ((array->len + len) > array->alloc)
1027     {
1028       guint old_alloc = array->alloc;
1029       array->alloc = g_nearest_pow (array->len + len);
1030       array->alloc = MAX (array->alloc, MIN_ARRAY_SIZE);
1031       array->pdata = g_realloc (array->pdata, sizeof (gpointer) * array->alloc);
1032       if (G_UNLIKELY (g_mem_gc_friendly))
1033         for ( ; old_alloc < array->alloc; old_alloc++)
1034           array->pdata [old_alloc] = NULL;
1035     }
1036 }
1037
1038 /**
1039  * g_ptr_array_set_size:
1040  * @array: a #GPtrArray.
1041  * @length: the new length of the pointer array.
1042  *
1043  * Sets the size of the array. When making the array larger,
1044  * newly-added elements will be set to %NULL. When making it smaller,
1045  * if @array has a non-%NULL #GDestroyNotify function then it will be
1046  * called for the removed elements.
1047  **/
1048 void
1049 g_ptr_array_set_size  (GPtrArray *farray,
1050                        gint       length)
1051 {
1052   GRealPtrArray* array = (GRealPtrArray*) farray;
1053
1054   g_return_if_fail (array);
1055
1056   if (length > array->len)
1057     {
1058       int i;
1059       g_ptr_array_maybe_expand (array, (length - array->len));
1060       /* This is not 
1061        *     memset (array->pdata + array->len, 0,
1062        *            sizeof (gpointer) * (length - array->len));
1063        * to make it really portable. Remember (void*)NULL needn't be
1064        * bitwise zero. It of course is silly not to use memset (..,0,..).
1065        */
1066       for (i = array->len; i < length; i++)
1067         array->pdata[i] = NULL;
1068     }
1069   else if (length < array->len)
1070     g_ptr_array_remove_range (farray, length, array->len - length);
1071
1072   array->len = length;
1073 }
1074
1075 /**
1076  * g_ptr_array_remove_index:
1077  * @array: a #GPtrArray.
1078  * @index_: the index of the pointer to remove.
1079  * @Returns: the pointer which was removed.
1080  *
1081  * Removes the pointer at the given index from the pointer array. The
1082  * following elements are moved down one place. If @array has a
1083  * non-%NULL #GDestroyNotify function it is called for the removed
1084  * element.
1085  **/
1086 gpointer
1087 g_ptr_array_remove_index (GPtrArray *farray,
1088                           guint      index_)
1089 {
1090   GRealPtrArray* array = (GRealPtrArray*) farray;
1091   gpointer result;
1092
1093   g_return_val_if_fail (array, NULL);
1094
1095   g_return_val_if_fail (index_ < array->len, NULL);
1096
1097   result = array->pdata[index_];
1098   
1099   if (array->element_free_func != NULL)
1100     array->element_free_func (array->pdata[index_]);
1101
1102   if (index_ != array->len - 1)
1103     g_memmove (array->pdata + index_, array->pdata + index_ + 1, 
1104                sizeof (gpointer) * (array->len - index_ - 1));
1105   
1106   array->len -= 1;
1107
1108   if (G_UNLIKELY (g_mem_gc_friendly))
1109     array->pdata[array->len] = NULL;
1110
1111   return result;
1112 }
1113
1114 /**
1115  * g_ptr_array_remove_index_fast:
1116  * @array: a #GPtrArray.
1117  * @index_: the index of the pointer to remove.
1118  * @Returns: the pointer which was removed.
1119  *
1120  * Removes the pointer at the given index from the pointer array. The
1121  * last element in the array is used to fill in the space, so this
1122  * function does not preserve the order of the array. But it is faster
1123  * than g_ptr_array_remove_index(). If @array has a non-%NULL
1124  * #GDestroyNotify function it is called for the removed element.
1125  **/
1126 gpointer
1127 g_ptr_array_remove_index_fast (GPtrArray *farray,
1128                                guint      index_)
1129 {
1130   GRealPtrArray* array = (GRealPtrArray*) farray;
1131   gpointer result;
1132
1133   g_return_val_if_fail (array, NULL);
1134
1135   g_return_val_if_fail (index_ < array->len, NULL);
1136
1137   result = array->pdata[index_];
1138
1139   if (array->element_free_func != NULL)
1140     array->element_free_func (array->pdata[index_]);
1141
1142   if (index_ != array->len - 1)
1143     array->pdata[index_] = array->pdata[array->len - 1];
1144
1145   array->len -= 1;
1146
1147   if (G_UNLIKELY (g_mem_gc_friendly))
1148     array->pdata[array->len] = NULL;
1149
1150   return result;
1151 }
1152
1153 /**
1154  * g_ptr_array_remove_range:
1155  * @array: a @GPtrArray.
1156  * @index_: the index of the first pointer to remove.
1157  * @length: the number of pointers to remove.
1158  *
1159  * Removes the given number of pointers starting at the given index
1160  * from a #GPtrArray.  The following elements are moved to close the
1161  * gap. If @array has a non-%NULL #GDestroyNotify function it is called
1162  * for the removed elements.
1163  *
1164  * Since: 2.4
1165  **/
1166 void
1167 g_ptr_array_remove_range (GPtrArray *farray,
1168                           guint      index_,
1169                           guint      length)
1170 {
1171   GRealPtrArray* array = (GRealPtrArray*) farray;
1172   guint n;
1173
1174   g_return_if_fail (array);
1175   g_return_if_fail (index_ < array->len);
1176   g_return_if_fail (index_ + length <= array->len);
1177
1178   if (array->element_free_func != NULL)
1179     {
1180       for (n = index_; n < index_ + length; n++)
1181         array->element_free_func (array->pdata[n]);
1182     }
1183
1184   if (index_ + length != array->len)
1185     {
1186       g_memmove (&array->pdata[index_],
1187                  &array->pdata[index_ + length], 
1188                  (array->len - (index_ + length)) * sizeof (gpointer));
1189     }
1190
1191   array->len -= length;
1192   if (G_UNLIKELY (g_mem_gc_friendly))
1193     {
1194       guint i;
1195       for (i = 0; i < length; i++)
1196         array->pdata[array->len + i] = NULL;
1197     }
1198 }
1199
1200 /**
1201  * g_ptr_array_remove:
1202  * @array: a #GPtrArray.
1203  * @data: the pointer to remove.
1204  * @Returns: %TRUE if the pointer is removed. %FALSE if the pointer is
1205  *           not found in the array.
1206  *
1207  * Removes the first occurrence of the given pointer from the pointer
1208  * array. The following elements are moved down one place. If @array
1209  * has a non-%NULL #GDestroyNotify function it is called for the
1210  * removed element.
1211  *
1212  * It returns %TRUE if the pointer was removed, or %FALSE if the
1213  * pointer was not found.
1214  **/
1215 gboolean
1216 g_ptr_array_remove (GPtrArray *farray,
1217                     gpointer   data)
1218 {
1219   GRealPtrArray* array = (GRealPtrArray*) farray;
1220   guint i;
1221
1222   g_return_val_if_fail (array, FALSE);
1223
1224   for (i = 0; i < array->len; i += 1)
1225     {
1226       if (array->pdata[i] == data)
1227         {
1228           g_ptr_array_remove_index (farray, i);
1229           return TRUE;
1230         }
1231     }
1232
1233   return FALSE;
1234 }
1235
1236 /**
1237  * g_ptr_array_remove_fast:
1238  * @array: a #GPtrArray.
1239  * @data: the pointer to remove.
1240  * @Returns: %TRUE if the pointer was found in the array.
1241  *
1242  * Removes the first occurrence of the given pointer from the pointer
1243  * array. The last element in the array is used to fill in the space,
1244  * so this function does not preserve the order of the array. But it is
1245  * faster than g_ptr_array_remove(). If @array has a non-%NULL
1246  * #GDestroyNotify function it is called for the removed element.
1247  *
1248  * It returns %TRUE if the pointer was removed, or %FALSE if the
1249  * pointer was not found.
1250  **/
1251 gboolean
1252 g_ptr_array_remove_fast (GPtrArray *farray,
1253                          gpointer   data)
1254 {
1255   GRealPtrArray* array = (GRealPtrArray*) farray;
1256   guint i;
1257
1258   g_return_val_if_fail (array, FALSE);
1259
1260   for (i = 0; i < array->len; i += 1)
1261     {
1262       if (array->pdata[i] == data)
1263         {
1264           g_ptr_array_remove_index_fast (farray, i);
1265           return TRUE;
1266         }
1267     }
1268
1269   return FALSE;
1270 }
1271
1272 /**
1273  * g_ptr_array_add:
1274  * @array: a #GPtrArray.
1275  * @data: the pointer to add.
1276  *
1277  * Adds a pointer to the end of the pointer array. The array will grow
1278  * in size automatically if necessary.
1279  **/
1280 void
1281 g_ptr_array_add (GPtrArray *farray,
1282                  gpointer   data)
1283 {
1284   GRealPtrArray* array = (GRealPtrArray*) farray;
1285
1286   g_return_if_fail (array);
1287
1288   g_ptr_array_maybe_expand (array, 1);
1289
1290   array->pdata[array->len++] = data;
1291 }
1292
1293 /**
1294  * g_ptr_array_sort:
1295  * @array: a #GPtrArray.
1296  * @compare_func: comparison function.
1297  *
1298  * Sorts the array, using @compare_func which should be a qsort()-style
1299  * comparison function (returns less than zero for first arg is less
1300  * than second arg, zero for equal, greater than zero if irst arg is
1301  * greater than second arg).
1302  *
1303  * If two array elements compare equal, their order in the sorted array
1304  * is undefined. If you want equal elements to keep their order (i.e.
1305  * you want a stable sort) you can write a comparison function that,
1306  * if two elements would otherwise compare equal, compares them by
1307  * their addresses.
1308  *
1309  * <note><para>The comparison function for g_ptr_array_sort() doesn't
1310  * take the pointers from the array as arguments, it takes pointers to
1311  * the pointers in the array.</para></note>
1312  **/
1313 void
1314 g_ptr_array_sort (GPtrArray    *array,
1315                   GCompareFunc  compare_func)
1316 {
1317   g_return_if_fail (array != NULL);
1318
1319   qsort (array->pdata,
1320          array->len,
1321          sizeof (gpointer),
1322          compare_func);
1323 }
1324
1325 /**
1326  * g_ptr_array_sort_with_data:
1327  * @array: a #GPtrArray.
1328  * @compare_func: comparison function.
1329  * @user_data: data to pass to @compare_func.
1330  *
1331  * Like g_ptr_array_sort(), but the comparison function has an extra
1332  * user data argument.
1333  *
1334  * <note><para>The comparison function for g_ptr_array_sort_with_data()
1335  * doesn't take the pointers from the array as arguments, it takes
1336  * pointers to the pointers in the array.</para></note>
1337  **/
1338 void
1339 g_ptr_array_sort_with_data (GPtrArray        *array,
1340                             GCompareDataFunc  compare_func,
1341                             gpointer          user_data)
1342 {
1343   g_return_if_fail (array != NULL);
1344
1345   g_qsort_with_data (array->pdata,
1346                      array->len,
1347                      sizeof (gpointer),
1348                      compare_func,
1349                      user_data);
1350 }
1351
1352 /**
1353  * g_ptr_array_foreach:
1354  * @array: a #GPtrArray
1355  * @func: the function to call for each array element
1356  * @user_data: user data to pass to the function
1357  * 
1358  * Calls a function for each element of a #GPtrArray.
1359  *
1360  * Since: 2.4
1361  **/
1362 void
1363 g_ptr_array_foreach (GPtrArray *array,
1364                      GFunc      func,
1365                      gpointer   user_data)
1366 {
1367   guint i;
1368
1369   g_return_if_fail (array);
1370
1371   for (i = 0; i < array->len; i++)
1372     (*func) (array->pdata[i], user_data);
1373 }
1374
1375 /**
1376  * SECTION:arrays_byte
1377  * @title: Byte Arrays
1378  * @short_description: arrays of bytes
1379  *
1380  * #GByteArray is a mutable array of bytes based on #GArray, to provide arrays
1381  * of bytes which grow automatically as elements are added.
1382  *
1383  * To create a new #GByteArray use g_byte_array_new(). To add elements to a
1384  * #GByteArray, use g_byte_array_append(), and g_byte_array_prepend().
1385  *
1386  * To set the size of a #GByteArray, use g_byte_array_set_size().
1387  *
1388  * To free a #GByteArray, use g_byte_array_free().
1389  *
1390  * <example>
1391  *  <title>Using a #GByteArray</title>
1392  *  <programlisting>
1393  *   GByteArray *gbarray;
1394  *   gint i;
1395  *
1396  *   gbarray = g_byte_array_new (<!-- -->);
1397  *   for (i = 0; i &lt; 10000; i++)
1398  *     g_byte_array_append (gbarray, (guint8*) "abcd", 4);
1399  *
1400  *   for (i = 0; i &lt; 10000; i++)
1401  *     {
1402  *       g_assert (gbarray->data[4*i] == 'a');
1403  *       g_assert (gbarray->data[4*i+1] == 'b');
1404  *       g_assert (gbarray->data[4*i+2] == 'c');
1405  *       g_assert (gbarray->data[4*i+3] == 'd');
1406  *     }
1407  *
1408  *   g_byte_array_free (gbarray, TRUE);
1409  *  </programlisting>
1410  * </example>
1411  *
1412  * See #GBytes if you are interested in an immutable object representing a
1413  * sequence of bytes.
1414  **/
1415
1416 /**
1417  * GByteArray:
1418  * @data: a pointer to the element data. The data may be moved as
1419  *        elements are added to the #GByteArray.
1420  * @len: the number of elements in the #GByteArray.
1421  *
1422  * The <structname>GByteArray</structname> struct allows access to the
1423  * public fields of a <structname>GByteArray</structname>.
1424  **/
1425
1426 /**
1427  * g_byte_array_new:
1428  * @Returns: the new #GByteArray.
1429  *
1430  * Creates a new #GByteArray with a reference count of 1.
1431  **/
1432 GByteArray* g_byte_array_new (void)
1433 {
1434   return (GByteArray*) g_array_sized_new (FALSE, FALSE, 1, 0);
1435 }
1436
1437 /**
1438  * g_byte_array_new_take:
1439  * @data: (array length=len): byte data for the array
1440  * @len: length of @data
1441  *
1442  * Create byte array containing the data. The data will be owned by the array
1443  * and will be freed with g_free(), i.e. it could be allocated using g_strdup().
1444  *
1445  * Since: 2.32
1446  *
1447  * Returns: (transfer full): a new #GByteArray
1448  */
1449 GByteArray *
1450 g_byte_array_new_take (guint8 *data,
1451                        gsize   len)
1452 {
1453   GByteArray *array;
1454   GRealArray *real;
1455
1456   array = g_byte_array_new ();
1457   real = (GRealArray *)array;
1458   g_assert (real->data == NULL);
1459   g_assert (real->len == 0);
1460
1461   real->data = data;
1462   real->len = len;
1463
1464   return array;
1465 }
1466
1467 /**
1468  * g_byte_array_sized_new:
1469  * @reserved_size: number of bytes preallocated.
1470  * @Returns: the new #GByteArray.
1471  *
1472  * Creates a new #GByteArray with @reserved_size bytes preallocated.
1473  * This avoids frequent reallocation, if you are going to add many
1474  * bytes to the array. Note however that the size of the array is still
1475  * 0.
1476  **/
1477 GByteArray* g_byte_array_sized_new (guint reserved_size)
1478 {
1479   return (GByteArray*) g_array_sized_new (FALSE, FALSE, 1, reserved_size);
1480 }
1481
1482 /**
1483  * g_byte_array_free:
1484  * @array: a #GByteArray.
1485  * @free_segment: if %TRUE the actual byte data is freed as well.
1486  * @Returns: the element data if @free_segment is %FALSE, otherwise
1487  *           %NULL.  The element data should be freed using g_free().
1488  *
1489  * Frees the memory allocated by the #GByteArray. If @free_segment is
1490  * %TRUE it frees the actual byte data. If the reference count of
1491  * @array is greater than one, the #GByteArray wrapper is preserved but
1492  * the size of @array will be set to zero.
1493  **/
1494 guint8*     g_byte_array_free     (GByteArray *array,
1495                                    gboolean    free_segment)
1496 {
1497   return (guint8*) g_array_free ((GArray*) array, free_segment);
1498 }
1499
1500 /**
1501  * g_byte_array_free_to_bytes:
1502  * @array: (transfer full): a #GByteArray
1503  *
1504  * Transfers the data from the #GByteArray into a new immutable #GBytes.
1505  *
1506  * The #GByteArray is freed unless the reference count of @array is greater
1507  * than one, the #GByteArray wrapper is preserved but the size of @array
1508  * will be set to zero.
1509  *
1510  * This is identical to using g_bytes_new_take() and g_byte_array_free()
1511  * together.
1512  *
1513  * Since: 2.32
1514  *
1515  * Returns: (transfer full): a new immutable #GBytes representing same byte
1516  *          data that was in the array
1517  */
1518 GBytes *
1519 g_byte_array_free_to_bytes (GByteArray *array)
1520 {
1521   gsize length;
1522
1523   g_return_val_if_fail (array != NULL, NULL);
1524
1525   length = array->len;
1526   return g_bytes_new_take (g_byte_array_free (array, FALSE), length);
1527 }
1528
1529 /**
1530  * g_byte_array_ref:
1531  * @array: A #GByteArray.
1532  *
1533  * Atomically increments the reference count of @array by one. This
1534  * function is MT-safe and may be called from any thread.
1535  *
1536  * Returns: The passed in #GByteArray.
1537  *
1538  * Since: 2.22
1539  **/
1540 GByteArray *
1541 g_byte_array_ref (GByteArray *array)
1542 {
1543   return (GByteArray *) g_array_ref ((GArray *) array);
1544 }
1545
1546 /**
1547  * g_byte_array_unref:
1548  * @array: A #GByteArray.
1549  *
1550  * Atomically decrements the reference count of @array by one. If the
1551  * reference count drops to 0, all memory allocated by the array is
1552  * released. This function is MT-safe and may be called from any
1553  * thread.
1554  *
1555  * Since: 2.22
1556  **/
1557 void
1558 g_byte_array_unref (GByteArray *array)
1559 {
1560   g_array_unref ((GArray *) array);
1561 }
1562
1563 /**
1564  * g_byte_array_append:
1565  * @array: a #GByteArray.
1566  * @data: the byte data to be added.
1567  * @len: the number of bytes to add.
1568  * @Returns: the #GByteArray.
1569  *
1570  * Adds the given bytes to the end of the #GByteArray. The array will
1571  * grow in size automatically if necessary.
1572  **/
1573 GByteArray* g_byte_array_append   (GByteArray   *array,
1574                                    const guint8 *data,
1575                                    guint         len)
1576 {
1577   g_array_append_vals ((GArray*) array, (guint8*)data, len);
1578
1579   return array;
1580 }
1581
1582 /**
1583  * g_byte_array_prepend:
1584  * @array: a #GByteArray.
1585  * @data: the byte data to be added.
1586  * @len: the number of bytes to add.
1587  * @Returns: the #GByteArray.
1588  *
1589  * Adds the given data to the start of the #GByteArray. The array will
1590  * grow in size automatically if necessary.
1591  **/
1592 GByteArray* g_byte_array_prepend  (GByteArray   *array,
1593                                    const guint8 *data,
1594                                    guint         len)
1595 {
1596   g_array_prepend_vals ((GArray*) array, (guint8*)data, len);
1597
1598   return array;
1599 }
1600
1601 /**
1602  * g_byte_array_set_size:
1603  * @array: a #GByteArray.
1604  * @length: the new size of the #GByteArray.
1605  * @Returns: the #GByteArray.
1606  *
1607  * Sets the size of the #GByteArray, expanding it if necessary.
1608  **/
1609 GByteArray* g_byte_array_set_size (GByteArray *array,
1610                                    guint       length)
1611 {
1612   g_array_set_size ((GArray*) array, length);
1613
1614   return array;
1615 }
1616
1617 /**
1618  * g_byte_array_remove_index:
1619  * @array: a #GByteArray.
1620  * @index_: the index of the byte to remove.
1621  * @Returns: the #GByteArray.
1622  *
1623  * Removes the byte at the given index from a #GByteArray. The
1624  * following bytes are moved down one place.
1625  **/
1626 GByteArray* g_byte_array_remove_index (GByteArray *array,
1627                                        guint       index_)
1628 {
1629   g_array_remove_index ((GArray*) array, index_);
1630
1631   return array;
1632 }
1633
1634 /**
1635  * g_byte_array_remove_index_fast:
1636  * @array: a #GByteArray.
1637  * @index_: the index of the byte to remove.
1638  * @Returns: the #GByteArray.
1639  *
1640  * Removes the byte at the given index from a #GByteArray. The last
1641  * element in the array is used to fill in the space, so this function
1642  * does not preserve the order of the #GByteArray. But it is faster
1643  * than g_byte_array_remove_index().
1644  **/
1645 GByteArray* g_byte_array_remove_index_fast (GByteArray *array,
1646                                             guint       index_)
1647 {
1648   g_array_remove_index_fast ((GArray*) array, index_);
1649
1650   return array;
1651 }
1652
1653 /**
1654  * g_byte_array_remove_range:
1655  * @array: a @GByteArray.
1656  * @index_: the index of the first byte to remove.
1657  * @length: the number of bytes to remove.
1658  * @Returns: the #GByteArray.
1659  *
1660  * Removes the given number of bytes starting at the given index from a
1661  * #GByteArray.  The following elements are moved to close the gap.
1662  *
1663  * Since: 2.4
1664  **/
1665 GByteArray*
1666 g_byte_array_remove_range (GByteArray *array,
1667                            guint       index_,
1668                            guint       length)
1669 {
1670   g_return_val_if_fail (array, NULL);
1671   g_return_val_if_fail (index_ < array->len, NULL);
1672   g_return_val_if_fail (index_ + length <= array->len, NULL);
1673
1674   return (GByteArray *)g_array_remove_range ((GArray*) array, index_, length);
1675 }
1676
1677 /**
1678  * g_byte_array_sort:
1679  * @array: a #GByteArray.
1680  * @compare_func: comparison function.
1681  *
1682  * Sorts a byte array, using @compare_func which should be a
1683  * qsort()-style comparison function (returns less than zero for first
1684  * arg is less than second arg, zero for equal, greater than zero if
1685  * first arg is greater than second arg).
1686  *
1687  * If two array elements compare equal, their order in the sorted array
1688  * is undefined. If you want equal elements to keep their order (i.e.
1689  * you want a stable sort) you can write a comparison function that,
1690  * if two elements would otherwise compare equal, compares them by
1691  * their addresses.
1692  **/
1693 void
1694 g_byte_array_sort (GByteArray   *array,
1695                    GCompareFunc  compare_func)
1696 {
1697   g_array_sort ((GArray *) array, compare_func);
1698 }
1699
1700 /**
1701  * g_byte_array_sort_with_data:
1702  * @array: a #GByteArray.
1703  * @compare_func: comparison function.
1704  * @user_data: data to pass to @compare_func.
1705  *
1706  * Like g_byte_array_sort(), but the comparison function takes an extra
1707  * user data argument.
1708  **/
1709 void
1710 g_byte_array_sort_with_data (GByteArray       *array,
1711                              GCompareDataFunc  compare_func,
1712                              gpointer          user_data)
1713 {
1714   g_array_sort_with_data ((GArray *) array, compare_func, user_data);
1715 }