Change pointers for heap allocation
[muddle-interpreter.git] / src / alloc.c
1 /*
2 Copyright (C) 2017-2018 Keziah Wesley
3
4 You can redistribute and/or modify this file under the terms of the
5 GNU Affero General Public License as published by the Free Software
6 Foundation, either version 3 of the License, or (at your option) any
7 later version.
8
9 This file is distributed in the hope that it will be useful, but
10 WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Affero General Public License for more details.
13
14 You should have received a copy of the GNU Affero General Public
15 License along with this file. If not, see
16 <http://www.gnu.org/licenses/>.
17 */
18
19 #include "alloc.h"
20 #include "object.h"
21
22 extern pool_object *pool;
23 extern pool_ptr ptop;
24
25 extern object *vhp_base;
26 extern heap_ptr vhp;
27
28 pool_ptr
29 pool_alloc (uint32_t len)
30 {
31   pool_ptr p = ptop;
32   ptop += len;
33   return p;
34 }
35
36 pool_object *
37 POOL_OBJECT (pool_ptr p)
38 {
39   if (!p)
40     return (pool_object *) 0;
41   return &pool[p];
42 }
43
44 pool_ptr
45 pool_copy_array_rev (const pool_object * objs, uint32_t len)
46 {
47   if (!len)
48     return 0;
49   pool_ptr p = pool_alloc (len);
50   for (int i = 0; i < len; i++)
51     {
52       pool[p + i] = (pool_object)
53       {
54       .type = objs[len - i - 1].type,.rest = p + i + 1,.val =
55           objs[len - i - 1].val};
56     }
57   pool[p + len - 1].rest = 0;
58   return p;
59 }
60
61 object *
62 HEAP_OBJECT (heap_ptr p)
63 {
64   assert (p > 0);
65   return &vhp_base[p];
66 }
67
68 heap_ptr
69 heap_alloc (uint32_t len)
70 {
71   enum
72   { DOPE_LEN = 1 };
73   heap_ptr p = vhp;
74   vhp += len + DOPE_LEN;
75   return p;
76 }
77
78 heap_ptr
79 heap_copy_array_rev (const object * objs, uint32_t len)
80 {
81   heap_ptr p = heap_alloc (len);
82   object *xs = HEAP_OBJECT (p);
83   for (int i = 0; i < (int) len; i++)
84     {
85       xs[i] = objs[len - 1 - (unsigned) i];
86     }
87   return p;
88 }