(* Writing text and numbers to standard output, through a buffer of Sys.outSize bytes. The buffer is written out when it is full, at each line feed when standard output is a terminal or lines asks it, by flush, and when the program ends by Rt.exit. C's stdio keeps a buffer of its own: a program that writes with both flushes one before writing with the other. A lock keeps what each call writes together when threads write at once. *) module Out; import Rt, Sys, Lock; var buf: [Sys.outSize]U8; n: INT; (* bytes in buf *) eachLine: BOOL; (* written at each line feed: at first, if standard output is a terminal *) lock: Lock.Lock; (* Writes out the buffer, with the lock held. What can't be written is dropped. *) proc out; var i, k: INT; begin i := 0; while i < n do k := Sys.write(Sys.stdout, buf[i..n]); if k > 0 then i := i + k; elsif k # Sys.errIntr then break; (* a signal broke in: try again *) end; end; n := 0; end; (* Writes out what the buffer holds. *) proc flush*; begin Lock.take(lock); out; Lock.give(lock); end; (* Has the buffer written at each line feed, whatever standard output is, or, if not on, only when it is full: for a program that filters a stream that comes slowly, through a pipe, as grep's --line-buffered. *) proc lines*(on: BOOL); begin Lock.take(lock); eachLine := on; Lock.give(lock); end; (* Writes the bytes of s. *) proc str*(s: []const U8); var i: INT; begin Lock.take(lock); for i := 0 to LEN(s) - 1 do if n = LEN(buf) then out; end; buf[n] := s[i]; INC(n); if (s[i] = '\n') and eachLine then out; end; end; Lock.give(lock); end; (* Writes the byte c. *) proc char*(c: U8); var b: [1]U8; begin b[0] := c; str(b); end; (* Writes a line feed. *) proc ln*; begin char('\n'); end; (* n in decimal *) proc int*(n: I64); var buf: [20]U8; i: INT; u: U64; begin u := U64(n); if n < 0 then u := 0 - u; end; i := 20; repeat i := i - 1; buf[i] := U8(u mod 10) + '0'; u := u div 10; until u = 0; if n < 0 then i := i - 1; buf[i] := '-'; end; str(buf[i..20]); end; (* n in hexadecimal, digits digits at least *) proc hex*(n: U64; digits: INT); var buf: [16]U8; i: INT; d: U8; begin i := 16; repeat i := i - 1; d := U8(n & 15); if d < 10 then buf[i] := d + '0'; else buf[i] := d - 10 + 'A'; end; n := n shr 4; digits := digits - 1; until (n = 0) and (digits <= 0) or (i = 0); str(buf[i..16]); end; begin eachLine := Sys.isTerminal(Sys.stdout); _ := Rt.atExit(flush); end Out.