(* Memory: Allocator, the interface every allocator offers, and pages from the system. NEW(p, a) calls a^.alloc. *) module Mem; import Sys, Rt; import SYSTEM; type Allocator* = record alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* or nil *) free*: proc(a: ^Allocator; p: ^U8); end; const (* The size of a page of memory, in bytes. *) Page* = 4096; (* size bytes, rounded up to whole pages, zeroed; or nil. *) proc pages*(size: INT): ^U8; begin return Sys.mmap((size + Page - 1) div Page * Page); end; (* Gives back to the system the pages that pages gave as p, given the same size. *) proc unmap*(p: ^U8; size: INT); begin Sys.munmap(p, (size + Page - 1) div Page * Page); end; (* a^.alloc(a, size, align): size bytes from a, at a multiple of align; or nil. *) proc alloc*(a: ^Allocator; size, align: INT): ^U8; begin return a^.alloc(a, size, align); end; (* a^.free(a, p): gives p back to a, which gave it. *) proc free*(a: ^Allocator; p: ^U8); begin a^.free(a, p); end; (* The module's test. *) proc main*; var p: ^U8; i: INT; begin p := pages(10000); if p = nil then Rt.stop("Mem.pages"); end; for i := 0 to 12287 do if p[i] # 0 then Rt.stop("Mem.pages: not zeroed"); end; end; p[12287] := 1; unmap(p, 10000); end; end Mem.