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