raz / site / content / advanced / 06-allocators.txt

179 lines · 5.2 KiB · raw · history · last change a5145f64

1title: Writing an allocator
2part: The library
3summary: Mem.Allocator is two procedures; make one over a fixed array, and one that counts.
4---
5An allocator is a record of two procedures, and that is all `Mem.Allocator` is:
6
7```text
8type Allocator* = record
9 alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* nil if out of room *)
10 free*: proc(a: ^Allocator; p: ^U8);
11end;
12```
13
14`NEW(p, a)` calls `a^.alloc(a, SIZE(T), alignment)` and zeroes what it gets. `Buf`, `List` and `Map` call the same procedures. So anything that fills in these two fields is an allocator, and everything in the library works with it.
15
16## An allocator over a fixed array
17
18Here is one that needs no system calls at all: it hands out memory from an array in the program, a bump allocator. This is the kind a program with no operating system, or no room for a heap, uses. `free` has nothing to do; `reset` forgets everything.
19
20The trick that lets one procedure find its state is the same one `Arena` uses: the record puts `base: Mem.Allocator` first, so a `^Mem.Allocator` and a `^Bump` are the same address, and the procedure converts one to the other.
21
22```raz Bump
23module Bump;
24import Mem;
25import SYSTEM;
26
27type
28 Bump* = record
29 base*: Mem.Allocator; (* first, so that ^Bump(a) finds the rest *)
30 mem: ^U8;
31 size, used*: INT;
32 end;
33
34proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8;
35var b: ^Bump; at: INT;
36begin
37 b := ^Bump(a);
38 at := (b^.used + align - 1) div align * align; (* round up to align *)
39 if (size < 0) or (at + size > b^.size) then return nil; end;
40 b^.used := at + size;
41 return b^.mem + at;
42end;
43
44proc free(_a: ^Mem.Allocator; _p: ^U8);
45begin
46end;
47
48(* a bump allocator over the size bytes at mem *)
49proc init*(b: ^Bump; mem: ^U8; size: INT);
50begin
51 b^.base := {alloc: alloc, free: free};
52 b^.mem := mem;
53 b^.size := size;
54 b^.used := 0;
55end;
56
57(* everything forgotten, the memory used again *)
58proc reset*(b: ^Bump);
59begin
60 b^.used := 0;
61end;
62
63end Bump.
64```
65
66```raz Bumping run
67module Bumping;
68import Out, Bump;
69import SYSTEM;
70
71type Point = record x, y: INT; end;
72
73var arena: [256]U8; (* the allocator's whole world *)
74
75proc main*;
76var b: Bump.Bump; p, q: ^Point; many: INT; r: ^Point;
77begin
78 Bump.init(SYSTEM.ADR(b), SYSTEM.ADR(arena[0]), 256);
79 NEW(p, SYSTEM.ADR(b.base));
80 NEW(q, SYSTEM.ADR(b.base));
81 p^.x := 1; q^.y := 2;
82 Out.int(b.used); Out.str(" bytes used by two points\n");
83 many := 2;
84 repeat
85 NEW(r, SYSTEM.ADR(b.base));
86 if r # nil then INC(many); end;
87 until r = nil;
88 Out.int(many); Out.str(" points fit in 256 bytes\n");
89 Bump.reset(SYSTEM.ADR(b));
90 NEW(r, SYSTEM.ADR(b.base));
91 if r # nil then Out.str("room again after a reset\n"); end;
92end;
93
94end Bumping.
95```
96
97An allocator that runs out says so with `nil`, and the caller decides what that means. Nothing else in the program is touched.
98
99## An allocator that counts
100
101An allocator can wrap another. This one forwards to whatever it is given and keeps count, which is how to find out what a piece of code allocates, or to prove that a path allocates nothing.
102
103```raz Counted
104module Counted;
105import Mem;
106import SYSTEM;
107
108type
109 Counted* = record
110 base*: Mem.Allocator; (* first *)
111 inner: ^Mem.Allocator;
112 allocs*, frees*, bytes*: INT;
113 end;
114
115proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8;
116var c: ^Counted; p: ^U8;
117begin
118 c := ^Counted(a);
119 p := Mem.alloc(c^.inner, size, align);
120 if p # nil then INC(c^.allocs); INC(c^.bytes, size); end;
121 return p;
122end;
123
124proc free(a: ^Mem.Allocator; p: ^U8);
125var c: ^Counted;
126begin
127 c := ^Counted(a);
128 INC(c^.frees);
129 Mem.free(c^.inner, p);
130end;
131
132(* a counting allocator in front of inner *)
133proc init*(c: ^Counted; inner: ^Mem.Allocator);
134begin
135 c^.base := {alloc: alloc, free: free};
136 c^.inner := inner;
137 c^.allocs := 0;
138 c^.frees := 0;
139 c^.bytes := 0;
140end;
141
142end Counted.
143```
144
145```raz Audit run
146module Audit;
147import Fmt, Heap, Mem, Buf, Counted, Names := List([]const U8);
148import SYSTEM;
149
150proc main*;
151var c: Counted.Counted; b: Buf.Buf; l: Names.List; i: INT; p: ^U8;
152begin
153 Counted.init(SYSTEM.ADR(c), Heap.heap);
154 Buf.init(b, SYSTEM.ADR(c.base));
155 for i := 1 to 200 do Buf.str(b, "0123456789"); end;
156 Fmt.print("a buffer of {} bytes took {} allocations\n",
157 [Fmt.int(b.len), Fmt.int(c.allocs)]);
158 Buf.done(b);
159
160 Names.init(l, SYSTEM.ADR(c.base));
161 for i := 1 to 10 do _ := Names.push(l, "x"); end;
162 Fmt.print("{} allocations in all, {} frees so far\n", [Fmt.int(c.allocs), Fmt.int(c.frees)]);
163 Names.clear(l);
164 Fmt.print("{} frees after clear\n", [Fmt.int(c.frees)]);
165
166 p := Mem.alloc(SYSTEM.ADR(c.base), 64, 8);
167 Mem.free(SYSTEM.ADR(c.base), p);
168end;
169
170end Audit.
171```
172
173A `Buf` grows by doubling, so two thousand bytes took a handful of allocations and not two hundred. That is the sort of thing a counting allocator is for.
174
175## What to take from this
176
177- An allocator is a value, so it is passed, wrapped, swapped in a test and replaced by a bump allocator in a program with no heap.
178- A library function that needs memory takes the allocator as a parameter, so its caller owns the policy.
179- An allocator can use the record-first trick to carry any state it needs, because converting a pointer to a record's first field and back is the same address.