raz / sbcl / lib / Buf.raz

75 lines · 1.5 KiB · raw · history · last change 55bc6c0d

1(* A growable byte buffer, its memory from the allocator init gives it. *)
2module Buf;
3import Mem;
4
5type Buf* = record
6 len*: INT;
7 data: ^U8;
8 cap: INT;
9 a: ^Mem.Allocator;
10end;
11
12proc init*(b: ^Buf; a: ^Mem.Allocator);
13begin
14 b^.len := 0;
15 b^.data := nil;
16 b^.cap := 0;
17 b^.a := a;
18end;
19
20(* room for n more bytes; false if the allocator has none *)
21proc room*(b: ^Buf; n: INT): BOOL;
22var cap: INT; p: ^U8;
23begin
24 if b^.len + n <= b^.cap then return true; end;
25 cap := b^.cap * 2;
26 if cap < 64 then cap := 64; end;
27 while cap < b^.len + n do cap := cap * 2; end;
28 p := Mem.alloc(b^.a, cap, 1);
29 if p = nil then return false; end;
30 if b^.len > 0 then COPY(p[0..b^.len], b^.data[0..b^.len]); end;
31 if b^.data # nil then Mem.free(b^.a, b^.data); end;
32 b^.data := p;
33 b^.cap := cap;
34 return true;
35end;
36
37proc add*(b: ^Buf; c: U8);
38begin
39 if room(b, 1) then
40 b^.data[b^.len] := c;
41 INC(b^.len);
42 end;
43end;
44
45proc str*(b: ^Buf; s: []U8);
46begin
47 if room(b, LEN(s)) then
48 COPY(b^.data[b^.len..b^.len + LEN(s)], s);
49 b^.len := b^.len + LEN(s);
50 end;
51end;
52
53(* what it holds, until it next grows *)
54proc bytes*(b: ^Buf): []U8;
55begin
56 if b^.data = nil then return ""; end;
57 return b^.data[0..b^.len];
58end;
59
60(* emptied, its memory kept *)
61proc reset*(b: ^Buf);
62begin
63 b^.len := 0;
64end;
65
66(* its memory given back *)
67proc done*(b: ^Buf);
68begin
69 if b^.data # nil then Mem.free(b^.a, b^.data); end;
70 b^.data := nil;
71 b^.len := 0;
72 b^.cap := 0;
73end;
74
75end Buf.