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