raz / lib / Arena.raz

90 lines · 2.4 KiB · raw · history · last change e0d008cd

1(* An allocator that hands out memory from one block and frees it all
2 at once: free does nothing, reset forgets everything. An Arena is
3 its allocator: SYSTEM.ADR(arena.base) is the ^Mem.Allocator to give NEW. *)
4module Arena;
5import Mem, Rt;
6import SYSTEM;
7
8type
9 Arena* = record
10 base*: Mem.Allocator; (* first, so that ^Arena(a) finds the rest *)
11 buf: ^U8;
12 used, cap: INT;
13 end;
14
15proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8;
16var ar: ^Arena; at: INT;
17begin
18 ar := ^Arena(a);
19 at := (ar^.used + align - 1) div align * align;
20 if (size < 0) or (at + size > ar^.cap) then return nil; end;
21 ar^.used := at + size;
22 return ar^.buf + at;
23end;
24
25proc free(_a: ^Mem.Allocator; _p: ^U8);
26begin
27end;
28
29(* An arena of size bytes; false if the system has none. *)
30proc init*(var ar: Arena; size: INT): BOOL;
31begin
32 ar.base := {alloc: alloc, free: free};
33 ar.buf := Mem.pages(size);
34 ar.used := 0;
35 ar.cap := size;
36 if ar.buf = nil then ar.cap := 0; end;
37 return ar.buf # nil;
38end;
39
40(* Where ar stands now, for release. *)
41proc mark*(const ar: Arena): INT;
42begin
43 return ar.used;
44end;
45
46(* Everything allocated from ar since mark m freed at once; a mark past
47 where it stands stops the program. *)
48proc release*(var ar: Arena; m: INT);
49begin
50 if (m < 0) or (m > ar.used) then Rt.stop("Arena.release: mark past the arena's end"); end;
51 ar.used := m;
52end;
53
54(* Forgets every allocation; the memory is used again. *)
55proc reset*(var ar: Arena);
56begin
57 release(ar, 0);
58end;
59
60(* Gives the arena's block back to the system; what it handed out is
61 gone with it. *)
62proc done*(var ar: Arena);
63begin
64 if ar.buf # nil then Mem.unmap(ar.buf, ar.cap); end;
65 ar.buf := nil;
66 ar.cap := 0;
67end;
68
69(* The module's test. *)
70proc main*;
71var ar: Arena; a: ^Mem.Allocator; p, q: ^U8; m: INT;
72begin
73 if not init(ar, 4096) then Rt.stop("Arena.init"); end;
74 a := SYSTEM.ADR(ar.base);
75 p := Mem.alloc(a, 3, 1);
76 q := Mem.alloc(a, 8, 8);
77 if (p = nil) or (q # p + 8) then Rt.stop("Arena: alignment"); end;
78 if Mem.alloc(a, 5000, 1) # nil then Rt.stop("Arena: too big"); end;
79 if Mem.alloc(a, -1, 1) # nil then Rt.stop("Arena: negative"); end;
80 reset(ar);
81 if Mem.alloc(a, 4096, 1) # p then Rt.stop("Arena.reset"); end;
82 m := mark(ar);
83 p := Mem.alloc(a, 100, 1);
84 q := Mem.alloc(a, 100, 1);
85 release(ar, m);
86 if (mark(ar) # m) or (Mem.alloc(a, 100, 1) # p) then Rt.stop("Arena.release"); end;
87 done(ar);
88end;
89
90end Arena.