raz / lib / Mem.raz

56 lines · 1.3 KiB · raw · history · last change e0d008cd

1(* Memory: Allocator, the interface every allocator offers, and pages
2 from the system. NEW(p, a) calls a^.alloc. *)
3module Mem;
4import Sys, Rt;
5import SYSTEM;
6
7type
8 Allocator* = record
9 alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* or nil *)
10 free*: proc(a: ^Allocator; p: ^U8);
11 end;
12
13const
14 (* The size of a page of memory, in bytes. *)
15 Page* = 4096;
16
17(* size bytes, rounded up to whole pages, zeroed; or nil. *)
18proc pages*(size: INT): ^U8;
19begin
20 return Sys.mmap((size + Page - 1) div Page * Page);
21end;
22
23(* Gives back to the system the pages that pages gave as p, given the
24 same size. *)
25proc unmap*(p: ^U8; size: INT);
26begin
27 Sys.munmap(p, (size + Page - 1) div Page * Page);
28end;
29
30(* a^.alloc(a, size, align): size bytes from a, at a multiple of
31 align; or nil. *)
32proc alloc*(a: ^Allocator; size, align: INT): ^U8;
33begin
34 return a^.alloc(a, size, align);
35end;
36
37(* a^.free(a, p): gives p back to a, which gave it. *)
38proc free*(a: ^Allocator; p: ^U8);
39begin
40 a^.free(a, p);
41end;
42
43(* The module's test. *)
44proc main*;
45var p: ^U8; i: INT;
46begin
47 p := pages(10000);
48 if p = nil then Rt.stop("Mem.pages"); end;
49 for i := 0 to 12287 do
50 if p[i] # 0 then Rt.stop("Mem.pages: not zeroed"); end;
51 end;
52 p[12287] := 1;
53 unmap(p, 10000);
54end;
55
56end Mem.