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