raz / lib / Out.raz

117 lines · 2.6 KiB · raw · history · last change e0d008cd

1(* Writing text and numbers to standard output, through a buffer of
2 Sys.outSize bytes. The buffer is written out when it is full, at
3 each line feed when standard output is a terminal or lines asks it,
4 by flush, and
5 when the program ends by Rt.exit. C's stdio keeps a buffer of its
6 own: a program that writes with both flushes one before writing
7 with the other. A lock keeps what each call writes together when
8 threads write at once. *)
9module Out;
10import Rt, Sys, Lock;
11
12var
13 buf: [Sys.outSize]U8;
14 n: INT; (* bytes in buf *)
15 eachLine: BOOL; (* written at each line feed: at first, if standard output is a terminal *)
16 lock: Lock.Lock;
17
18(* Writes out the buffer, with the lock held. What can't be written is
19 dropped. *)
20proc out;
21var i, k: INT;
22begin
23 i := 0;
24 while i < n do
25 k := Sys.write(Sys.stdout, buf[i..n]);
26 if k > 0 then i := i + k;
27 elsif k # Sys.errIntr then break; (* a signal broke in: try again *)
28 end;
29 end;
30 n := 0;
31end;
32
33(* Writes out what the buffer holds. *)
34proc flush*;
35begin
36 Lock.take(lock);
37 out;
38 Lock.give(lock);
39end;
40
41(* Has the buffer written at each line feed, whatever standard output
42 is, or, if not on, only when it is full: for a program that filters
43 a stream that comes slowly, through a pipe, as grep's
44 --line-buffered. *)
45proc lines*(on: BOOL);
46begin
47 Lock.take(lock);
48 eachLine := on;
49 Lock.give(lock);
50end;
51
52(* Writes the bytes of s. *)
53proc str*(s: []const U8);
54var i: INT;
55begin
56 Lock.take(lock);
57 for i := 0 to LEN(s) - 1 do
58 if n = LEN(buf) then out; end;
59 buf[n] := s[i];
60 INC(n);
61 if (s[i] = '\n') and eachLine then out; end;
62 end;
63 Lock.give(lock);
64end;
65
66(* Writes the byte c. *)
67proc char*(c: U8);
68var b: [1]U8;
69begin
70 b[0] := c;
71 str(b);
72end;
73
74(* Writes a line feed. *)
75proc ln*;
76begin
77 char('\n');
78end;
79
80(* n in decimal *)
81proc int*(n: I64);
82var buf: [20]U8; i: INT; u: U64;
83begin
84 u := U64(n);
85 if n < 0 then u := 0 - u; end;
86 i := 20;
87 repeat
88 i := i - 1;
89 buf[i] := U8(u mod 10) + '0';
90 u := u div 10;
91 until u = 0;
92 if n < 0 then
93 i := i - 1;
94 buf[i] := '-';
95 end;
96 str(buf[i..20]);
97end;
98
99(* n in hexadecimal, digits digits at least *)
100proc hex*(n: U64; digits: INT);
101var buf: [16]U8; i: INT; d: U8;
102begin
103 i := 16;
104 repeat
105 i := i - 1;
106 d := U8(n & 15);
107 if d < 10 then buf[i] := d + '0'; else buf[i] := d - 10 + 'A'; end;
108 n := n shr 4;
109 digits := digits - 1;
110 until (n = 0) and (digits <= 0) or (i = 0);
111 str(buf[i..16]);
112end;
113
114begin
115 eachLine := Sys.isTerminal(Sys.stdout);
116 _ := Rt.atExit(flush);
117end Out.