1c4ab0ac9a844ed2e733400439a5135729f708d2
[libfirm] / ir / adt / array.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/adt/array.c
4  * Purpose:     Array --- dynamic & flexible arrays.
5  * Author:      Markus Armbruster
6  * Modified by:
7  * Created:     1999 by getting from fiasco
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 1995, 1996 Markus Armbruster
10  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
11  */
12
13 #ifdef HAVE_CONFIG_H
14 # include <config.h>
15 #endif
16
17 #include <stdlib.h>
18 #include "array.h"
19
20 /* Undefine the macros to get the functions instead, cf tmalloc.c.  */
21 #undef xmalloc
22 #undef xrealloc
23 #undef xstrdup
24 #undef xfree
25
26
27 _arr_descr arr_mt_descr
28 #ifndef NDEBUG
29   = { ARR_D_MAGIC }
30 #endif
31 ;
32
33 void *
34 _new_arr_d (struct obstack *obstack, int nelts, size_t elts_size)
35 {
36   _arr_descr *new;
37
38   assert (obstack && (nelts >= 0));
39
40   new = obstack_alloc (obstack, _ARR_ELTS_OFFS+elts_size);
41   _ARR_SET_DBGINF (new, ARR_D_MAGIC, elts_size/nelts);
42   new->u.obstack = obstack;
43   new->nelts = nelts;
44   return new->v.elts;
45 }
46
47
48 void *
49 _new_arr_f (int nelts, size_t elts_size)
50 {
51   _arr_descr *new;
52
53   assert (nelts >= 0);
54   new = xmalloc (_ARR_ELTS_OFFS+elts_size);
55   _ARR_SET_DBGINF (new, ARR_F_MAGIC, nelts ? elts_size/nelts : 0);
56   new->u.allocated = new->nelts = nelts;
57   return new->v.elts;
58 }
59
60
61 void
62 _del_arr_f (void *elts)
63 {
64   _arr_descr *dp = _ARR_DESCR (elts);
65
66   ARR_VRFY (elts);
67   assert (dp->cookie == ARR_F_MAGIC);
68
69 #ifndef NDEBUG
70   dp->cookie = 0xdeadbeef;
71 #endif
72   free (dp);
73 }
74
75
76 void *
77 _arr_setlen (void *elts, int nelts, size_t elts_size)
78 {
79   _arr_descr *dp = _ARR_DESCR (elts);
80
81   assert ((dp->cookie == ARR_F_MAGIC) && (nelts >= 0));
82   ARR_VRFY (elts);
83   assert (!dp->eltsize || !nelts || (dp->eltsize == elts_size/nelts));
84
85   dp = xrealloc (dp, _ARR_ELTS_OFFS+elts_size);
86   dp->u.allocated = dp->nelts = nelts;
87
88   return dp->v.elts;
89 }
90
91 \
92 void *
93 _arr_resize (void *elts, int nelts, size_t eltsize)
94 {
95   _arr_descr *dp = _ARR_DESCR (elts);
96   int n;
97
98   assert ((dp->cookie == ARR_F_MAGIC) && (nelts >= 0));
99   ARR_VRFY (elts);
100   assert (dp->eltsize ? dp->eltsize == eltsize : (dp->eltsize = eltsize, 1));
101
102   /* @@@ lots of resizes for small nelts */
103   n = MAX (1, dp->u.allocated);
104   while (nelts > n) n <<= 1;
105   while (3*nelts < n) n >>= 1;
106   assert (n >= nelts);
107
108   if (n != dp->u.allocated) {
109     dp = xrealloc (dp, _ARR_ELTS_OFFS+eltsize*n);
110     dp->u.allocated = n;
111 #if defined(DEBUG) && defined(HAVE_GNU_MALLOC)
112   } else {
113     tmalloc_tag = NULL;
114 #endif
115   }
116   dp->nelts = nelts;
117
118   return dp->v.elts;
119 }