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