Pristine Ack-5.5
[Ack-5.5.git] / util / LLgen / src / alloc.c
1 /* Copyright (c) 1991 by the Vrije Universiteit, Amsterdam, the Netherlands.
2  * For full copyright and restrictions on use see the file COPYING in the top
3  * level of the LLgen tree.
4  */
5
6 /*
7  *  L L G E N
8  *
9  *  An Extended LL(1) Parser Generator
10  *
11  *  Author : Ceriel J.H. Jacobs
12  */
13
14 /*
15  * alloc.c
16  * Interface to malloc() and realloc()
17  */
18
19 # include "types.h"
20 # include "extern.h"
21
22 # ifndef NORCSID
23 static string rcsid = "$Id: alloc.c,v 2.10 1997/02/21 11:27:40 ceriel Exp $";
24 # endif
25
26 static string e_nomem = "Out of memory";
27
28 p_mem
29 alloc(size) unsigned size; {
30         /*
31            Allocate "size" bytes. Panic if it fails
32          */
33         p_mem   p;
34         p_mem   malloc();
35
36         if ((p = malloc(size)) == 0) fatal(linecount,e_nomem);
37         return p;
38 }
39
40 p_mem
41 ralloc(p,size) p_mem p; unsigned size; {
42         /*
43            Re-allocate the chunk of memory indicated by "p", to
44            occupy "size" bytes
45          */
46         p_mem   realloc();
47
48         if ((p = realloc(p,size)) == 0) fatal(linecount,e_nomem);
49         return p;
50 }
51
52 p_mem
53 new_mem(p) register p_info p; {
54         /*
55            This routine implements arrays that can grow.
56            It must be called every time a new element is added to it.
57            Also, the array has associated with it a "info_alloc" structure,
58            which contains info on the element size, total allocated size,
59            a pointer to the array, a pointer to the first free element,
60            and a pointer to the top.
61            If the base of the array is remembered elsewhere, it should
62            be updated each time this routine is called
63          */
64         p_mem   rp;
65         unsigned sz;
66
67         if (p->i_max >= p->i_top) {     /* No more free elements */
68                 sz = p->i_size;
69                 if (sizeof(char *) > 2) {
70                         /*
71                            Do not worry about size. Just double it.
72                          */
73                         p->i_size += p->i_size;
74                         if (! p->i_size)
75                                 p->i_size += p->i_incr * p->i_esize;
76                         }
77                 else {
78                         /*
79                            Worry about size, so only increment in chunks of i_incr.
80                          */
81                         p->i_size += p->i_incr * p->i_esize;
82                 }
83                 p->i_ptr = !p->i_ptr ?
84                         alloc(p->i_size) :
85                         ralloc(p->i_ptr, p->i_size);
86                 p->i_max = p->i_ptr + sz;
87                 p->i_top = p->i_ptr + p->i_size;
88         }
89         rp = p->i_max;
90         p->i_max += p->i_esize;
91         return rp;
92 }