(* An allocator that hands out memory from one block and frees it all at once: free does nothing, reset forgets everything. An Arena is its allocator: SYSTEM.ADR(arena.base) is the ^Mem.Allocator to give NEW. *) module Arena; import Mem, Rt; import SYSTEM; type Arena* = record base*: Mem.Allocator; (* first, so that ^Arena(a) finds the rest *) buf: ^U8; used, cap: INT; end; proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8; var ar: ^Arena; at: INT; begin ar := ^Arena(a); at := (ar^.used + align - 1) div align * align; if (size < 0) or (at + size > ar^.cap) then return nil; end; ar^.used := at + size; return ar^.buf + at; end; proc free(_a: ^Mem.Allocator; _p: ^U8); begin end; (* An arena of size bytes; false if the system has none. *) proc init*(var ar: Arena; size: INT): BOOL; begin ar.base := {alloc: alloc, free: free}; ar.buf := Mem.pages(size); ar.used := 0; ar.cap := size; if ar.buf = nil then ar.cap := 0; end; return ar.buf # nil; end; (* Where ar stands now, for release. *) proc mark*(const ar: Arena): INT; begin return ar.used; end; (* Everything allocated from ar since mark m freed at once; a mark past where it stands stops the program. *) proc release*(var ar: Arena; m: INT); begin if (m < 0) or (m > ar.used) then Rt.stop("Arena.release: mark past the arena's end"); end; ar.used := m; end; (* Forgets every allocation; the memory is used again. *) proc reset*(var ar: Arena); begin release(ar, 0); end; (* Gives the arena's block back to the system; what it handed out is gone with it. *) proc done*(var ar: Arena); begin if ar.buf # nil then Mem.unmap(ar.buf, ar.cap); end; ar.buf := nil; ar.cap := 0; end; (* The module's test. *) proc main*; var ar: Arena; a: ^Mem.Allocator; p, q: ^U8; m: INT; begin if not init(ar, 4096) then Rt.stop("Arena.init"); end; a := SYSTEM.ADR(ar.base); p := Mem.alloc(a, 3, 1); q := Mem.alloc(a, 8, 8); if (p = nil) or (q # p + 8) then Rt.stop("Arena: alignment"); end; if Mem.alloc(a, 5000, 1) # nil then Rt.stop("Arena: too big"); end; if Mem.alloc(a, -1, 1) # nil then Rt.stop("Arena: negative"); end; reset(ar); if Mem.alloc(a, 4096, 1) # p then Rt.stop("Arena.reset"); end; m := mark(ar); p := Mem.alloc(a, 100, 1); q := Mem.alloc(a, 100, 1); release(ar, m); if (mark(ar) # m) or (Mem.alloc(a, 100, 1) # p) then Rt.stop("Arena.release"); end; done(ar); end; end Arena.