(* A growable byte buffer, its memory from the allocator init gives it. *) module Buf; import Mem; type Buf* = record len*: INT; data: ^U8; cap: INT; a: ^Mem.Allocator; end; proc init*(b: ^Buf; a: ^Mem.Allocator); begin b^.len := 0; b^.data := nil; b^.cap := 0; b^.a := a; end; (* room for n more bytes; false if the allocator has none *) proc room*(b: ^Buf; n: INT): BOOL; var cap: INT; p: ^U8; begin if b^.len + n <= b^.cap then return true; end; cap := b^.cap * 2; if cap < 64 then cap := 64; end; while cap < b^.len + n do cap := cap * 2; end; p := Mem.alloc(b^.a, cap, 1); if p = nil then return false; end; if b^.len > 0 then COPY(p[0..b^.len], b^.data[0..b^.len]); end; if b^.data # nil then Mem.free(b^.a, b^.data); end; b^.data := p; b^.cap := cap; return true; end; proc add*(b: ^Buf; c: U8); begin if room(b, 1) then b^.data[b^.len] := c; INC(b^.len); end; end; proc str*(b: ^Buf; s: []U8); begin if room(b, LEN(s)) then COPY(b^.data[b^.len..b^.len + LEN(s)], s); b^.len := b^.len + LEN(s); end; end; (* what it holds, until it next grows *) proc bytes*(b: ^Buf): []U8; begin if b^.data = nil then return ""; end; return b^.data[0..b^.len]; end; (* emptied, its memory kept *) proc reset*(b: ^Buf); begin b^.len := 0; end; (* its memory given back *) proc done*(b: ^Buf); begin if b^.data # nil then Mem.free(b^.a, b^.data); end; b^.data := nil; b^.len := 0; b^.cap := 0; end; end Buf.