| 1 | (* Writing text and numbers to standard output, buffered: written out when |
| 2 | the buffer is full, at each line feed when standard output is a |
| 3 | terminal, at flush, and when the program ends by Rt.exit. A lock keeps |
| 4 | what each call writes together. *) |
| 5 | module Out; |
| 6 | import Sys, Rt, Lock; |
| 7 | |
| 8 | const hexDigits = "0123456789ABCDEF"; |
| 9 | |
| 10 | var |
| 11 | buf: [Sys.outSize]U8; |
| 12 | len: INT; |
| 13 | lock: Lock.Lock; |
| 14 | terminal: BOOL; |
| 15 | |
| 16 | (* The buffer written out; the lock is held. *) |
| 17 | proc drain; |
| 18 | var n, done: INT; |
| 19 | begin |
| 20 | while done < len do |
| 21 | n := Sys.write(Sys.stdout, buf[done..len]); |
| 22 | if n <= 0 then len := 0; return; end; |
| 23 | done := done + n; |
| 24 | end; |
| 25 | len := 0; |
| 26 | end; |
| 27 | |
| 28 | (* s added to the buffer; the lock is held *) |
| 29 | proc put(s: []U8); |
| 30 | var i, n: INT; |
| 31 | begin |
| 32 | while i < LEN(s) do |
| 33 | if len = LEN(buf) then drain; end; |
| 34 | n := LEN(s) - i; |
| 35 | if n > LEN(buf) - len then n := LEN(buf) - len; end; |
| 36 | COPY(buf[len..len + n], s[i..i + n]); |
| 37 | len := len + n; |
| 38 | i := i + n; |
| 39 | end; |
| 40 | end; |
| 41 | |
| 42 | proc str*(s: []U8); |
| 43 | var i: INT; |
| 44 | begin |
| 45 | Lock.take(ADR(lock)); |
| 46 | put(s); |
| 47 | if terminal then |
| 48 | for i := 0 to LEN(s) - 1 do |
| 49 | if s[i] = 10 then drain; break; end; |
| 50 | end; |
| 51 | end; |
| 52 | Lock.give(ADR(lock)); |
| 53 | end; |
| 54 | |
| 55 | proc char*(c: U8); |
| 56 | var b: [1]U8; |
| 57 | begin |
| 58 | b[0] := c; |
| 59 | str(b); |
| 60 | end; |
| 61 | |
| 62 | (* a line feed *) |
| 63 | proc ln*; |
| 64 | begin |
| 65 | str("\n"); |
| 66 | end; |
| 67 | |
| 68 | (* n in decimal *) |
| 69 | proc int*(n: I64); |
| 70 | var digits: [20]U8; i: INT; u: U64; |
| 71 | begin |
| 72 | u := U64(n); |
| 73 | if n < 0 then u := 0 - u; end; |
| 74 | i := LEN(digits); |
| 75 | repeat |
| 76 | DEC(i); |
| 77 | digits[i] := U8(u mod 10) + '0'; |
| 78 | u := u div 10; |
| 79 | until u = 0; |
| 80 | if n < 0 then DEC(i); digits[i] := '-'; end; |
| 81 | str(digits[i..LEN(digits)]); |
| 82 | end; |
| 83 | |
| 84 | (* n in hexadecimal, digits digits at least *) |
| 85 | proc hex*(n: U64; digits: INT); |
| 86 | var d: [16]U8; i: INT; |
| 87 | begin |
| 88 | i := LEN(d); |
| 89 | repeat |
| 90 | DEC(i); |
| 91 | d[i] := hexDigits[INT(n & 0FH)]; |
| 92 | n := n shr 4; |
| 93 | until n = 0; |
| 94 | while i > LEN(d) - digits and i > 0 do DEC(i); d[i] := '0'; end; |
| 95 | str(d[i..LEN(d)]); |
| 96 | end; |
| 97 | |
| 98 | proc flush*; |
| 99 | begin |
| 100 | Lock.take(ADR(lock)); |
| 101 | drain; |
| 102 | Lock.give(ADR(lock)); |
| 103 | end; |
| 104 | |
| 105 | begin |
| 106 | terminal := Sys.isTerminal(Sys.stdout); |
| 107 | _ := Rt.atExit(flush); |
| 108 | end Out. |