(* Formatted output. Each {} in the format takes the next argument: Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.real(x, 2)]); {{ and }} stand for { and }. A {} with no argument left prints nothing, and arguments left over are not printed. A width between the braces pads the argument to that many bytes: {3} on the left with spaces, {03} on the left with zeros (after a minus sign), {-3} on the right with spaces. A longer argument is written whole. A { followed by anything else is no width. Left out: precision, other fills, argument numbers and names. *) module Fmt; import Out, Buf, Arena, Rt, Sys; import SYSTEM; const Limb = 1000000000; (* a Big's base, 10^9 *) LimbDigits = 9; (* the decimal digits of a limb *) LimbsMax = 90; (* limbs of the largest Big: 769 digits, for the least F64's lo *) MostDigits = 17; (* digits that always read back as the F64 they came from *) MantBits = 52; (* an F64's fraction bits *) ExpBias = 1075; (* its exponent's bias, with the fraction a whole number *) ExpMask = 7FFH; (* its exponent's bits, shifted down *) TwoStep = 29; (* doublings at once: 10^9 * 2^29 < 2^63 *) FiveStep = 13; (* fives multiplied at once: 10^9 * 5^13 < 2^63 *) const ShortMost* = 24; (* the longest short: -2.2250738585072014E-308 *) type (* An argument, and how it is printed. A real has places digits after the point, at most 9, rounded to the nearest, half away from zero; from 1E15 on, it has the exponent that makes it less than 10, as 1.50E17; nan and inf are spelled so. *) Arg* = variant int(i: I64); (* in decimal *) uint(u: U64); (* in decimal *) hex(h: U64); (* in hexadecimal, capitals, no 0x *) lowHex(h: U64); (* in hexadecimal, lower case, no 0x *) str(s: []const U8); char(c: U8); (* the one byte *) bool(b: BOOL); (* true or false *) real(r: F64; places: INT); end; (* Where the pieces go: to out if slice is set, else to b, or to standard output if b is nil. n counts the bytes given, so a slice holds the first LEN(out) of them and the rest are cut. With dry set nothing is written and n only counts the bytes that would be, to know how much a width must pad. *) Sink = record b: ^Buf.Buf; out: []U8; slice, dry: BOOL; n: INT; end; (* What a {} says: its width, whether it pads with zeros, and whether on the right. *) Spec = record width: INT; zero, left: BOOL; end; (* A whole number, not negative, in base 10^9, the lowest limb first. *) Big = record v: [LimbsMax]U64; n: INT; (* the limbs in use *) end; (* A number above 0, exactly in decimal: 0.d times 10^e, its first digit not 0. *) Exact = record d: [LimbsMax * LimbDigits]U8; (* '0' to '9' *) n, e: INT; (* how many digits, and the exponent *) end; (* A number above 0 as short writes it, in the same way. *) Short = record d: [MostDigits]U8; n, e: INT; end; (* The digits of u in base, at the end of the array: it and where they start. Digits past 9 are letters from letter on, 'A' or 'a'. *) proc digits(u: U64; base: U64; letter: U8): ([24]U8, INT); var d: [24]U8; i: INT; v: U8; begin i := 24; repeat DEC(i); v := U8(u mod base); if v < 10 then d[i] := v + '0'; else d[i] := v - 10 + letter; end; u := u div base; until u = 0; return d, i; end; (* A sink that writes to b, or to standard output if b is nil. *) proc sink(b: ^Buf.Buf): Sink; var k: Sink; begin k.b := b; k.out := []; k.slice := false; k.dry := false; k.n := 0; return k; end; (* s to k. *) proc put(var k: Sink; s: []const U8); var at, room: INT; begin at := k.n; INC(k.n, LEN(s)); if k.dry then elsif k.slice then room := LEN(k.out) - at; (* what is past the end is cut *) if room > LEN(s) then room := LEN(s); end; if room > 0 then COPY(k.out[at..at + room], s[0..room]); end; elsif k.b = nil then Out.str(s); else Buf.str(k.b^, s); end; end; (* n copies of c to k. *) proc fill(var k: Sink; c: U8; n: INT); var one: [1]U8; i: INT; begin one[0] := c; for i := 1 to n do put(k, one); end; end; (* x as Arg's real says, but for the minus sign, which arg writes. The whole part and the fraction are taken apart, so that each fits an I64: hence the exponent from 1E15. *) proc putReal(var k: Sink; x: F64; places: INT); const zeros = "00000000"; var d: [24]U8; at, i, e: INT; scale, whole, frac: I64; begin if x # x then put(k, "nan"); return; end; if x < 0.0 then x := -x; end; if x > 1.7976931348623157E308 then put(k, "inf"); return; end; if places < 0 then places := 0; elsif places > 9 then places := 9; end; scale := 1; for i := 1 to places do scale := scale * 10; end; if x >= 1.0E15 then while x >= 10.0 do x := x / 10.0; INC(e); end; end; whole := I64(x); frac := I64((x - F64(whole)) * F64(scale) + 0.5); if frac = scale then INC(whole); frac := 0; end; if (e > 0) and (whole = 10) then whole := 1; INC(e); end; d, at := digits(U64(whole), 10, 'A'); put(k, d[at..24]); if places > 0 then put(k, "."); d, at := digits(U64(frac), 10, 'A'); put(k, zeros[0..places - (24 - at)]); put(k, d[at..24]); end; if e > 0 then d, at := digits(U64(e), 10, 'A'); put(k, "E"); put(k, d[at..24]); end; end; (* ---- short: the fewest digits that read back ---- An F64 x is m times 2^k, m and k whole numbers. Every number between the halves to the F64s on either side of x reads back as x, so short looks for the fewest digits that land between those halves, lo and hi: below lo x hi above the F64s around x |--------|------*------|--------| x, lo and hi are written out exactly in decimal, each an Exact, and compared digit by digit with each try, so nothing is rounded on the way. For p digits the tries are x cut to p digits and that one more in its last place: the two numbers of p digits nearest x. The first p for which one of them lies between lo and hi gives the answer; if both do, the nearer x is taken. 17 digits are always enough. An exact value is made in a Big, a whole number in base 10^9: for k at least 0, m times 2^k is m doubled k times; for k below 0, it is m times 5^-k with the point -k places from the right, since 2^-k is 5^-k / 10^-k. *) (* The bits of x. *) proc bits(x: F64): U64; var p: ^U64; begin p := ^U64(SYSTEM.ADR(x)); return p^; end; (* b times f, which is at most 2^31. *) proc bigMul(var b: Big; f: U64); var i: INT; t, carry: U64; begin carry := 0; for i := 0 to b.n - 1 do t := b.v[i] * f + carry; carry := t div Limb; b.v[i] := t - carry * Limb; end; while carry > 0 do b.v[b.n] := carry mod Limb; carry := carry div Limb; INC(b.n); end; end; (* b times 2^k, or 5^k if five, a few steps at once. *) proc bigPow(var b: Big; k: INT; five: BOOL); var step, i: INT; f: U64; begin while k > 0 do if five then step := FiveStep; else step := TwoStep; end; if k < step then step := k; end; f := 1; for i := 1 to step do if five then f := f * 5; else f := f * 2; end; end; bigMul(b, f); DEC(k, step); end; end; (* m times 2^k, m not 0, exactly in decimal, into w. *) proc expand(m: U64; k: INT; var w: Exact); var b: Big; d: [24]U8; at, i, j, point: INT; v: U64; begin b.n := 0; while m > 0 do b.v[b.n] := m mod Limb; m := m div Limb; INC(b.n); end; point := 0; if k < 0 then point := -k; bigPow(b, -k, true); else bigPow(b, k, false); end; (* the top limb without leading zeros, then nine digits a limb *) d, at := digits(b.v[b.n - 1], 10, 'A'); w.n := 24 - at; COPY(w.d[0..w.n], d[at..24]); for i := b.n - 2 to 0 by -1 do v := b.v[i]; for j := LimbDigits - 1 to 0 by -1 do w.d[w.n + j] := U8(v mod 10) + '0'; v := v div 10; end; INC(w.n, LimbDigits); end; w.e := w.n - point; end; (* -1, 0 or 1 as 0.d times 10^e, d's first digit not 0, is below, at or above w. *) proc compare(d: []const U8; e: INT; const w: Exact): INT; var i, n: INT; a, c: U8; begin if e # w.e then if e < w.e then return -1; end; return 1; end; n := w.n; if LEN(d) > n then n := LEN(d); end; for i := 0 to n - 1 do a := '0'; c := '0'; (* past its end each has zeros *) if i < LEN(d) then a := d[i]; end; if i < w.n then c := w.d[i]; end; if a # c then if a < c then return -1; end; return 1; end; end; return 0; end; (* Whether s reads back as the F64 that lo and hi are the halves around: it lies between them, or on one of them if ends, as the F64 whose m is even takes a tie. *) proc between(const s: Short; const lo, hi: Exact; ends: BOOL): BOOL; var below, above: INT; begin below := compare(s.d[0..s.n], s.e, lo); above := compare(s.d[0..s.n], s.e, hi); return ((below > 0) or (below = 0) and ends) and ((above < 0) or (above = 0) and ends); end; (* s one more in its last place, carrying, without the zeros that leaves at the end: 129 becomes 13, and 99 becomes 1 with the point moved. *) proc up(var s: Short); var i: INT; begin i := s.n - 1; while (i >= 0) and (s.d[i] = '9') do DEC(i); end; if i >= 0 then INC(s.d[i]); s.n := i + 1; else s.d[0] := '1'; s.n := 1; INC(s.e); end; end; (* Whether x, cut where rest begins, is nearer the number one more in the last place than to the cut one: rest is above a half, or a half and last, the cut one's last digit, odd. *) proc nearerUp(rest: []const U8; last: U8): BOOL; var i: INT; begin if rest[0] # '5' then return rest[0] > '5'; end; for i := 1 to LEN(rest) - 1 do if rest[i] # '0' then return true; end; end; return (last - '0') & 1 = 1; end; (* The fewest digits that read back as x, finite and above 0, into s. *) proc shortest(x: F64; var s: Short); var u, m: U64; k, p: INT; mid, lo, hi: Exact; ends, downOk, upOk: BOOL; next: Short; begin (* x as m times 2^k: the fraction with its hidden 1 but for the smallest exponent, the F64s below 2^-1022 *) u := bits(x); m := u & (U64(1) shl MantBits - 1); k := INT(u shr MantBits & ExpMask); if k = 0 then k := 1; else m := m | U64(1) shl MantBits; end; DEC(k, ExpBias); (* the halves to the F64s around x; the one below a power of two is half as far as the one above, but at the smallest exponent *) expand(m, k, mid); expand(2 * m + 1, k - 1, hi); if (m = U64(1) shl MantBits) and (k > 1 - ExpBias) then expand(4 * m - 1, k - 2, lo); else expand(2 * m - 1, k - 1, lo); end; ends := m & 1 = 0; for p := 1 to MostDigits do s.n := p; if p >= mid.n then s.n := mid.n; end; (* x itself has no more digits *) s.e := mid.e; COPY(s.d[0..s.n], mid.d[0..s.n]); if s.n = mid.n then return; end; next := s; up(next); downOk := between(s, lo, hi, ends); upOk := between(next, lo, hi, ends); if upOk and (not downOk or nearerUp(mid.d[p..mid.n], s.d[p - 1])) then s := next; return; elsif downOk then return; end; end; end; (* s added to out at n, which moves past it. *) proc emit(var out: [ShortMost]U8; var n: INT; s: []const U8); begin COPY(out[n..n + LEN(s)], s); INC(n, LEN(s)); end; (* x in the fewest digits Math.toReal reads back as x, the nearer of two such, and of two as near the one whose last digit is even, written into out from 0: those bytes. From 1E-4 to below 1E15 it is plain, as 0.0001, 0.1, 42 or 123456789012345; else a digit, a point and the rest, an E and the exponent, as 1.5E17 or 5E-324. Zero is 0 or -0, keeping its sign so that it too reads back; nan, inf and -inf are spelled so. The longest is ShortMost, 24 bytes, as -2.2250738585072014E-308: a sign, 17 digits, a point and E-308; the longest plain one, -0.00012345678901234567, has 22. *) proc short*(x: F64; var out: [ShortMost]U8): []U8; var s: Short; d: [24]U8; n, at, e, z: INT; begin n := 0; if x # x then emit(out, n, "nan"); return out[0..n]; end; if bits(x) shr 63 = 1 then emit(out, n, "-"); x := -x; end; (* -0.0 too *) if x > 1.7976931348623157E308 then emit(out, n, "inf"); return out[0..n]; end; if x = 0.0 then emit(out, n, "0"); return out[0..n]; end; shortest(x, s); if (s.e >= -3) and (s.e <= 15) then (* from 1E-4 to below 1E15 *) if s.e <= 0 then emit(out, n, "0."); for z := 1 to -s.e do emit(out, n, "0"); end; emit(out, n, s.d[0..s.n]); elsif s.e >= s.n then emit(out, n, s.d[0..s.n]); for z := 1 to s.e - s.n do emit(out, n, "0"); end; else emit(out, n, s.d[0..s.e]); emit(out, n, "."); emit(out, n, s.d[s.e..s.n]); end; else emit(out, n, s.d[0..1]); if s.n > 1 then emit(out, n, "."); emit(out, n, s.d[1..s.n]); end; emit(out, n, "E"); e := s.e - 1; if e < 0 then emit(out, n, "-"); e := -e; end; d, at := digits(U64(e), 10, 'A'); emit(out, n, d[at..24]); end; return out[0..n]; end; (* Whether a is printed with a minus sign. *) proc negative(a: Arg): BOOL; var neg: BOOL; begin match a of | int(i): neg := i < 0; | real(r, _places): neg := r < 0.0; | else: neg := false; end; return neg; end; (* a as Arg says, but for the minus sign. *) proc magnitude(var k: Sink; a: Arg); var d: [24]U8; at: INT; one: [1]U8; begin match a of | int(i): if i < 0 then d, at := digits(0 - U64(i), 10, 'A'); else d, at := digits(U64(i), 10, 'A'); end; put(k, d[at..24]); | uint(u): d, at := digits(u, 10, 'A'); put(k, d[at..24]); | hex(h): d, at := digits(h, 16, 'A'); put(k, d[at..24]); | lowHex(h): d, at := digits(h, 16, 'a'); put(k, d[at..24]); | str(s): put(k, s); | char(c): one[0] := c; put(k, one); | bool(t): if t then put(k, "true"); else put(k, "false"); end; | real(r, places): putReal(k, r, places); end; end; (* a as Arg says. *) proc arg(var k: Sink; a: Arg); begin if negative(a) then put(k, "-"); end; magnitude(k, a); end; (* a in a field of s.width bytes: on the left spaces, or zeros after the minus sign; or spaces on the right. A longer a is written whole. *) proc field(var k: Sink; a: Arg; const s: Spec); var dry: Sink; pad: INT; begin dry := sink(nil); dry.dry := true; arg(dry, a); pad := s.width - dry.n; if s.left then arg(k, a); fill(k, ' ', pad); elsif s.zero then if negative(a) then put(k, "-"); end; fill(k, '0', pad); magnitude(k, a); else fill(k, ' ', pad); arg(k, a); end; end; (* If f[i], a {, starts a width, {2}, {02} or {-10}: it is read into s and the place of its } is the result; else the result is -1. *) proc spec(f: []const U8; i: INT; var s: Spec): INT; var count: INT; begin s.width := 0; s.zero := false; s.left := false; INC(i); if (i < LEN(f)) and (f[i] = '-') then s.left := true; INC(i); end; if (i < LEN(f)) and (f[i] = '0') then s.zero := true; end; while (i < LEN(f)) and (f[i] >= '0') and (f[i] <= '9') and (count < 4) do s.width := s.width * 10 + INT(f[i] - '0'); INC(count); INC(i); end; if (count > 0) and (i < LEN(f)) and (f[i] = '}') then return i; end; return -1; end; (* f to k, each {} replaced by the next of args. *) proc format(var k: Sink; f: []const U8; args: []const Arg); var i, start, n, close: INT; s: Spec; begin i := 0; start := 0; n := 0; while i < LEN(f) do if (f[i] = '{') or (f[i] = '}') then put(k, f[start..i]); close := -1; if f[i] = '{' then close := spec(f, i, s); end; if (i + 1 < LEN(f)) and (f[i + 1] = f[i]) then put(k, f[i..i + 1]); INC(i); elsif (f[i] = '{') and (i + 1 < LEN(f)) and (f[i + 1] = '}') then if n < LEN(args) then arg(k, args[n]); end; INC(n); INC(i); elsif close >= 0 then if n < LEN(args) then field(k, args[n], s); end; INC(n); i := close; end; start := i + 1; end; INC(i); end; put(k, f[start..LEN(f)]); end; (* Writes f to standard output, each {} replaced by the next of args. *) proc print*(f: []const U8; args: []const Arg); var k: Sink; begin k := sink(nil); format(k, f, args); end; (* Writes f to standard error as print writes it, after flushing Out, so that what was printed before comes first. The text is made whole in a buffer and written at once, to stay together when threads write at once. The buffer is an arena's, not the heap's, so that a program that doesn't call eprint carries no heap for it; its pages are mapped as they are written, and a text of more than a megabyte stops the program, as a Buf does when it can't grow. *) proc eprint*(f: []const U8; args: []const Arg); var ar: Arena.Arena; b: Buf.Buf; k: Sink; s: []U8; n: INT; begin Out.flush; if not Arena.init(ar, 1 shl 20) then Rt.stop("Fmt.eprint: no arena"); end; Buf.init(b, SYSTEM.ADR(ar.base)); k := sink(SYSTEM.ADR(b)); format(k, f, args); s := Buf.bytes(b); while LEN(s) > 0 do n := Sys.write(Sys.stderr, s); if n > 0 then s := s[n..LEN(s)]; elsif n # Sys.errIntr then break; (* a signal broke in: try again *) end; end; Arena.done(ar); end; (* Appends f to b, each {} replaced by the next of args. *) proc write*(var b: Buf.Buf; f: []const U8; args: []const Arg); var k: Sink; begin k := sink(SYSTEM.ADR(b)); (* a sink's nil is standard output *) format(k, f, args); end; (* Formats f into out as write formats it: the bytes written, and false if out was too short and the text is cut there. It needs no memory of its own. *) proc into*(out: []U8; f: []const U8; args: []const Arg): (INT, BOOL); var k: Sink; begin k := sink(nil); k.out := out; k.slice := true; format(k, f, args); if k.n > LEN(out) then return LEN(out), false; end; return k.n, true; end; (* Each of xs, shorts, with a space between, added to b. *) proc shorts(var b: Buf.Buf; xs: []const F64); var d: [ShortMost]U8; i: INT; begin for i := 0 to LEN(xs) - 1 do if i > 0 then Buf.add(b, ' '); end; Buf.str(b, short(xs[i], d)); end; end; (* The module's test: formats into a buffer over an arena. *) proc main*; var ar: Arena.Arena; b: Buf.Buf; zero: F64; small: [8]U8; d: [ShortMost]U8; n: INT; whole: BOOL; begin if not Arena.init(ar, 1 shl 16) then Rt.stop("Fmt: no arena"); end; Buf.init(b, SYSTEM.ADR(ar.base)); write(b, "{} {} {} {}|{}{}{} {{}}", [int(-42), uint(0FFFFFFFFFFFFFFFFH), hex(48879), str("s"), char('c'), bool(true), int(0)]); if Buf.bytes(b) # "-42 18446744073709551615 BEEF s|ctrue0 {}" then Rt.stop("Fmt.write"); end; Buf.reset(b); write(b, "{} and {}", [int(1)]); if Buf.bytes(b) # "1 and " then Rt.stop("Fmt: too few arguments"); end; Buf.reset(b); write(b, "{} {} {} {} {} {} {} {}", [real(3.14159, 2), real(-2.5, 0), real(0.999, 2), real(0.05, 1), real(1.0, 12), real(-0.001, 2), real(123.0, 0), real(999999999999999.9, 0)]); if Buf.bytes(b) # "3.14 -3 1.00 0.1 1.000000000 -0.00 123 1000000000000000" then Rt.stop("Fmt.real"); end; Buf.reset(b); write(b, "{} {} {} {} {} {}", [real(1.5E17, 2), real(-9.999E20, 2), real(1.0E15, 0), real(1.7976931348623157E308, 3), real(1.0 / zero, 2), real(zero / zero, 2)]); if Buf.bytes(b) # "1.50E17 -1.00E21 1E15 1.798E308 inf nan" then Rt.stop("Fmt.real: an exponent"); end; Buf.reset(b); write(b, "[{3}][{03}][{-3}][{04}][{4}][{-4}|][{2}]", [int(7), int(7), int(7), int(-7), int(-7), int(-7), int(12345)]); if Buf.bytes(b) # "[ 7][007][7 ][-007][ -7][-7 |][12345]" then Rt.stop("Fmt: a width"); end; Buf.reset(b); write(b, "{6}|{-6}|{06}|{2}|{05}|{3}", [str("ab"), str("ab"), real(-1.5, 1), hex(255), lowHex(0ABCH), char('c')]); if Buf.bytes(b) # " ab|ab |-001.5|FF|00abc| c" then Rt.stop("Fmt: a width on other arguments"); end; Buf.reset(b); write(b, "{x} {2x} {0} {-} {a} {1", [int(1), int(2)]); if Buf.bytes(b) # "x 2x 1 - a 1" then Rt.stop("Fmt: a { that is no width"); end; Buf.reset(b); shorts(b, [0.1, 1.0 / 3.0, -2.5, 100.0, 42.0E3, 0.0001, 0.00012, 123456789012345.0]); if Buf.bytes(b) # "0.1 0.3333333333333333 -2.5 100 42000 0.0001 0.00012 123456789012345" then Rt.stop("Fmt.short"); end; Buf.reset(b); shorts(b, [1.0E15, 1.5E17, 9.9E-5, 5.0E-324, 1.7976931348623157E308, 2.2250738585072014E-308, 9007199254740992.0]); if Buf.bytes(b) # "1E15 1.5E17 9.9E-5 5E-324 1.7976931348623157E308 2.2250738585072014E-308 9.007199254740992E15" then Rt.stop("Fmt.short: an exponent"); end; Buf.reset(b); shorts(b, [zero, -zero, 1.0 / zero, -1.0 / zero, zero / zero]); write(b, " {6}|{-6}", [str(short(0.5, d)), str(short(0.5, d))]); if Buf.bytes(b) # "0 -0 inf -inf nan 0.5|0.5 " then Rt.stop("Fmt.short: zero, inf, nan and a width"); end; if LEN(short(-2.2250738585072014E-308, d)) # ShortMost then Rt.stop("Fmt.short: the longest"); end; n, whole := into(small, "{}:{02}", [int(-3), int(7)]); if (small[0..n] # "-3:07") or not whole then Rt.stop("Fmt.into"); end; n, whole := into(small, "line {}, {}", [int(12), str("x")]); if (small[0..n] # "line 12,") or whole then Rt.stop("Fmt.into: cut short"); end; n, whole := into(small[0..0], "{}", [int(1)]); if (n # 0) or whole then Rt.stop("Fmt.into: no room"); end; Arena.done(ar); end; end Fmt.