← core

core/fmt.kur

//! The writer protocol and the printing and formatting traits.
// core::fmt -- the writer protocol and formatting.
//
// Allocator-free: everything here works with any writer. `alloc::fmt`
// re-exports it and adds what needs `Buffer!`.
//
// `Writer[W]` is the output protocol: write one byte, a whole
// `Str['static]`, or raw bytes. Reading `'static` text needs no capability
// argument (`core::str::StaticRead`), so a bulk write of one can live in
// the trait itself and lets a writer copy literal segments in one step.
// `write_raw` is the bulk write for everything else: a caller that already
// holds the right to read some bytes passes them without a per-byte loop.
//
// Writers use sticky errors. A writer that can fail records its first
// failure and ignores every later write; its own `finish` reports the
// failure together with the underlying resource. Neither `Writer` nor
// `Format` carries an error type, so an f-string never has to infer one,
// and the writer and every threaded input always come back.
//
// Every writer has two methods beside the protocol (a blanket impl):
// `out.put(x)` prints `x` through `Printable[T, W]`, which uses `x` up, and
// `out.write(&cx, bytes)` copies the bytes of any view `cx` can read:
//
//     Buffer!::new().put("line ").put(n).put(": ").write(&cx, text)
//
// `Format[T, W]` formats a `T` into any writer `W` and hands the value back:
// formatting does not consume. The compiler expands `f"..."` into these
// calls -- literal segments, and `{x}` of type `Str['static]`, through
// `Writer::write_static`, every other `{x}` through `Format::format` -- so
// instances are written once, generically over the writer, and work with
// every writer.
//
// `f"...".write(out)` writes into `out` and hands it back.
// `f"...".write(&cx, out)` also lends the f-string the capability in the
// place `cx`: it is moved out of `cx`, wrapped with `out` as
// `ReadingWriter![W, C]::new(out, cx)`, every segment is written through
// the wrapper, so each `{text}` of type `Str['k]` reads through `cx`, and
// `finish` hands back the writer, the result, and the capability, which
// goes back into `cx`:
//
//     f"{name} = {value}".write(&cx, Buffer!::new())
//
// Floats. An `f64` or `f32` is written as the decimal with the fewest
// significant digits that reads back as the same float (`core::dtoa`), and
// of those the nearest: `0.1` for 0.1, `0.30000000000000004` for 0.1 + 0.2,
// `0.1` again for `0.1f32`. The digits are laid out as ECMAScript's
// `Number::toString` lays them out, with `e` before a bare exponent:
//
// - an integer below 10^21 in full, with no point: `2`, `100`,
//   `100000000000000000000`;
// - a number from 10^-6 below 10^21 with a point: `2.5`, `0.000001`;
// - anything else with an exponent: `1e21`, `1.5e300`, `1e-7`, `5e-324`;
// - `-` before a negative number and -0.0 (`-0`); `inf`, `-inf` and `NaN`.
//
// Every one of them reads back through `std::float::parse_f64` (C's
// `strtod`) as the float written, a NaN as some NaN.

use package as core;

use core::dtoa::{Decimal, shortest};
use core::slice::{ReadBytes, Readable};
use core::option::Option;
use core::str::Str;

/// A destination for bytes: the output protocol that f-strings and `Format`
/// write to.
forall Self.
trait Writer {
    /// Writes one byte.
    fn write_byte(self: Self, byte: u8) -> Self;
    /// Writes the bytes of `'static` text, such as a literal.
    fn write_static(self: Self, bytes: Str['static]) -> Self;
    /// Writes `len` bytes starting at `ptr`; the writer reads them before it
    /// returns and keeps no pointer to them. Caller: `ptr[0..len)` is
    /// readable for the whole call.
    unsafe fn write_raw(self: Self, ptr: *u8, len: usize) -> Self;
}

/// What every writer can do with the protocol: print a value into it, and
/// copy in the bytes of any view it can read.
forall W where Writer[W].
impl W {
    /// Prints `x` into the writer (`Printable`), using `x` up:
    /// `Buffer!::new().put("line ").put(n)`.
    forall T where Printable[T, W].
    fn put(self, x: T) -> W {
        Printable[T, W]::print(x, self)
    }

    /// Writes the bytes of any readable byte view, read through the
    /// capability that permits it. Never consumes the view itself.
    forall C, S where ReadBytes[C, S], Copy[S].
    fn write(self, &cx: C, bytes: S) -> W {
        let n = ReadBytes[C, S]::len(&cx, bytes);
        var o = self;
        var i = 0usize;
        while i < n {
            let b = ReadBytes[C, S]::get(&cx, bytes, i);
            let next = match b {
                Some(x) => Writer[W]::write_byte(o, x),
                None => o,
            };
            o = next;
            i = i + 1usize;
        }
        o
    }
}

/// Writes the decimal digits of `n`, most significant first.
forall W where Writer[W].
fn write_u64(out: W, n: u64) -> W {
    let ten = 10u64;
    let rest = n / ten;
    let o = if rest != 0u64 {
        write_u64(out, rest)
    } else {
        out
    };
    let digit = ((n % ten) as u8) + b'0';
    Writer[W]::write_byte(o, digit)
}

/// Writes the decimal digits of `n`, after a `-` when it is negative.
forall W where Writer[W].
fn write_i64(out: W, n: i64) -> W {
    if n < 0i64 {
        let o = Writer[W]::write_byte(out, 45u8);
        // Two's-complement negation in `u64`, so `i64::MIN` has a magnitude.
        let magnitude = 0u64 - (n as u64);
        write_u64(o, magnitude)
    } else {
        write_u64(out, (n as u64))
    }
}

/// Writes `x` as the shortest decimal that reads back as it (see
/// "Floats" in the module notes): `2.5`, `0.1`, `100`, `1e21`, `5e-324`,
/// `-0`, `inf`, `-inf`, `NaN`.
forall W where Writer[W].
fn write_f64(out: W, x: f64) -> W {
    if x.is_nan() {
        return Writer[W]::write_static(out, "NaN");
    }
    let bits = x.to_bits();
    let o = if x.is_sign_negative() { Writer[W]::write_byte(out, b'-') } else { out };
    let biased = (bits >> 52u64) & 2047u64;
    let fraction = bits & 4503599627370495u64;
    if biased == 2047u64 {
        return Writer[W]::write_static(o, "inf");
    }
    if biased == 0u64 && fraction == 0u64 {
        return Writer[W]::write_byte(o, b'0');
    }
    let decimal = if biased == 0u64 {
        shortest(fraction, -1074i32, false)
    } else {
        // The implicit leading bit; the gap below is the smaller at the bottom of a binade.
        shortest(fraction | 4503599627370496u64, (biased as i32) - 1075i32, fraction == 0u64 && biased > 1u64)
    };
    write_decimal(o, decimal)
}

/// Writes `x` as the shortest decimal that reads back as it as an `f32`,
/// as `write_f64` does for an `f64`: `0.1f32` is `0.1`.
forall W where Writer[W].
fn write_f32(out: W, x: f32) -> W {
    if x.is_nan() {
        return Writer[W]::write_static(out, "NaN");
    }
    let bits = x.to_bits();
    let o = if x.is_sign_negative() { Writer[W]::write_byte(out, b'-') } else { out };
    let biased = (bits >> 23u32) & 255u32;
    let fraction = (bits & 8388607u32) as u64;
    if biased == 255u32 {
        return Writer[W]::write_static(o, "inf");
    }
    if biased == 0u32 && fraction == 0u64 {
        return Writer[W]::write_byte(o, b'0');
    }
    let decimal = if biased == 0u32 {
        shortest(fraction, -149i32, false)
    } else {
        shortest(fraction | 8388608u64, (biased as i32) - 150i32, fraction == 0u64 && biased > 1u32)
    };
    write_decimal(o, decimal)
}

/// A positive decimal laid out as ECMAScript's `Number::toString` does: an
/// integer of at most 21 digits in full, a number from 10^-6 on positionally,
/// anything else as `d.ddde±x`.
forall W where Writer[W].
fn write_decimal(out: W, decimal: Decimal) -> W {
    let { digits, count, point } = decimal;
    let n = count as i32;
    if n <= point && point <= 21i32 {
        let o = write_digits(out, digits, count, 0u32, count);
        write_zeros(o, (point - n) as u32)
    } else if 0i32 < point && point <= 21i32 {
        let o = write_digits(out, digits, count, 0u32, point as u32);
        write_digits(Writer[W]::write_byte(o, b'.'), digits, count, point as u32, count)
    } else if -6i32 < point && point <= 0i32 {
        let o = write_zeros(Writer[W]::write_static(out, "0."), (0i32 - point) as u32);
        write_digits(o, digits, count, 0u32, count)
    } else {
        let o = write_digits(out, digits, count, 0u32, 1u32);
        let o = if count > 1u32 { write_digits(Writer[W]::write_byte(o, b'.'), digits, count, 1u32, count) } else { o };
        write_i64(Writer[W]::write_byte(o, b'e'), ((point - 1i32) as i64))
    }
}

/// Writes the digits `from` to `to` of the `count` decimal digits of `digits`, most significant first.
forall W where Writer[W].
fn write_digits(out: W, digits: u64, count: u32, from: u32, to: u32) -> W {
    var o = out;
    var i = from;
    while i < to {
        var unit = 1u64;
        var j = i + 1u32;
        while j < count {
            unit = unit * 10u64;
            j = j + 1u32;
        }
        o = Writer[W]::write_byte(o, (((digits / unit) % 10u64) as u8) + b'0');
        i = i + 1u32;
    }
    o
}

/// Writes `n` zeros.
forall W where Writer[W].
fn write_zeros(out: W, n: u32) -> W {
    var o = out;
    var i = 0u32;
    while i < n {
        o = Writer[W]::write_byte(o, b'0');
        i = i + 1u32;
    }
    o
}

/// Formatting of a `T` into any writer `W`, handing the value back.
forall T, W.
trait Format {
    /// Writes `value` to `out`, handing both back.
    fn format(value: T, out: W) -> (T, W);
}

/// A `u8` formats as its decimal digits.
forall W where Writer[W].
instance Format[u8, W] {
    fn format(value: u8, out: W) -> (u8, W) {
        (value, write_u64(out, (value as u64)))
    }
}

/// A `u16` formats as its decimal digits.
forall W where Writer[W].
instance Format[u16, W] {
    fn format(value: u16, out: W) -> (u16, W) {
        (value, write_u64(out, (value as u64)))
    }
}

/// A `u32` formats as its decimal digits.
forall W where Writer[W].
instance Format[u32, W] {
    fn format(value: u32, out: W) -> (u32, W) {
        (value, write_u64(out, (value as u64)))
    }
}

/// A `u64` formats as its decimal digits.
forall W where Writer[W].
instance Format[u64, W] {
    fn format(value: u64, out: W) -> (u64, W) {
        (value, write_u64(out, value))
    }
}

/// A `usize` formats as its decimal digits.
forall W where Writer[W].
instance Format[usize, W] {
    fn format(value: usize, out: W) -> (usize, W) {
        (value, write_u64(out, (value as u64)))
    }
}

/// A `i8` formats as its decimal digits, after `-` when negative.
forall W where Writer[W].
instance Format[i8, W] {
    fn format(value: i8, out: W) -> (i8, W) {
        (value, write_i64(out, (value as i64)))
    }
}

/// A `i16` formats as its decimal digits, after `-` when negative.
forall W where Writer[W].
instance Format[i16, W] {
    fn format(value: i16, out: W) -> (i16, W) {
        (value, write_i64(out, (value as i64)))
    }
}

/// A `i32` formats as its decimal digits, after `-` when negative.
forall W where Writer[W].
instance Format[i32, W] {
    fn format(value: i32, out: W) -> (i32, W) {
        (value, write_i64(out, (value as i64)))
    }
}

/// A `i64` formats as its decimal digits, after `-` when negative.
forall W where Writer[W].
instance Format[i64, W] {
    fn format(value: i64, out: W) -> (i64, W) {
        (value, write_i64(out, value))
    }
}

/// A `isize` formats as its decimal digits, after `-` when negative.
forall W where Writer[W].
instance Format[isize, W] {
    fn format(value: isize, out: W) -> (isize, W) {
        (value, write_i64(out, (value as i64)))
    }
}

/// An `f64` formats as the shortest decimal that reads back as it (`write_f64`).
forall W where Writer[W].
instance Format[f64, W] {
    fn format(value: f64, out: W) -> (f64, W) {
        (value, write_f64(out, value))
    }
}

/// An `f32` formats as the shortest decimal that reads back as it (`write_f32`).
forall W where Writer[W].
instance Format[f32, W] {
    fn format(value: f32, out: W) -> (f32, W) {
        (value, write_f32(out, value))
    }
}

/// A `bool` formats as `true` or `false`.
forall W where Writer[W].
instance Format[bool, W] {
    fn format(value: bool, out: W) -> (bool, W) {
        let text = if value { "true" } else { "false" };
        (value, Writer[W]::write_static(out, text))
    }
}

/// A value that can be printed into a writer `W`; printing uses it up.
///
/// `out.put(x)` prints through it, as does `std::io::print(x)`. Unlike
/// `Format`, which an f-string's `{x}` goes through, it hands nothing back,
/// so it can take an owned value, a `Buffer!`, and free it.
forall T, W.
trait Printable {
    /// Writes `value` to `out`.
    fn print(value: T, out: W) -> W;
}

/// `'static` text, such as a literal, prints as its bytes.
forall W where Writer[W].
instance Printable[Str['static], W] {
    fn print(value: Str['static], out: W) -> W {
        Writer[W]::write_static(out, value)
    }
}

/// A `u8` prints as its decimal digits.
forall W where Writer[W].
instance Printable[u8, W] {
    fn print(value: u8, out: W) -> W {
        write_u64(out, (value as u64))
    }
}

/// A `u16` prints as its decimal digits.
forall W where Writer[W].
instance Printable[u16, W] {
    fn print(value: u16, out: W) -> W {
        write_u64(out, (value as u64))
    }
}

/// A `u32` prints as its decimal digits.
forall W where Writer[W].
instance Printable[u32, W] {
    fn print(value: u32, out: W) -> W {
        write_u64(out, (value as u64))
    }
}

/// A `u64` prints as its decimal digits.
forall W where Writer[W].
instance Printable[u64, W] {
    fn print(value: u64, out: W) -> W {
        write_u64(out, value)
    }
}

/// A `usize` prints as its decimal digits.
forall W where Writer[W].
instance Printable[usize, W] {
    fn print(value: usize, out: W) -> W {
        write_u64(out, (value as u64))
    }
}

/// An `i8` prints as its decimal digits, after `-` when negative.
forall W where Writer[W].
instance Printable[i8, W] {
    fn print(value: i8, out: W) -> W {
        write_i64(out, (value as i64))
    }
}

/// An `i16` prints as its decimal digits, after `-` when negative.
forall W where Writer[W].
instance Printable[i16, W] {
    fn print(value: i16, out: W) -> W {
        write_i64(out, (value as i64))
    }
}

/// An `i32` prints as its decimal digits, after `-` when negative.
forall W where Writer[W].
instance Printable[i32, W] {
    fn print(value: i32, out: W) -> W {
        write_i64(out, (value as i64))
    }
}

/// An `i64` prints as its decimal digits, after `-` when negative.
forall W where Writer[W].
instance Printable[i64, W] {
    fn print(value: i64, out: W) -> W {
        write_i64(out, value)
    }
}

/// An `isize` prints as its decimal digits, after `-` when negative.
forall W where Writer[W].
instance Printable[isize, W] {
    fn print(value: isize, out: W) -> W {
        write_i64(out, (value as i64))
    }
}

/// An `f32` prints as the shortest decimal that reads back as it (`write_f32`).
forall W where Writer[W].
instance Printable[f32, W] {
    fn print(value: f32, out: W) -> W {
        write_f32(out, value)
    }
}

/// An `f64` prints as the shortest decimal that reads back as it (`write_f64`).
forall W where Writer[W].
instance Printable[f64, W] {
    fn print(value: f64, out: W) -> W {
        write_f64(out, value)
    }
}

/// A `bool` prints as `true` or `false`.
forall W where Writer[W].
instance Printable[bool, W] {
    fn print(value: bool, out: W) -> W {
        Writer[W]::write_static(out, if value { "true" } else { "false" })
    }
}

/// A borrowed byte view formats as its bytes, read through its capability.
forall C, S, W where ReadBytes[C, S], Copy[S], Writer[W].
instance Format[Readable[C, S], W] {
    fn format(value: Readable[C, S], out: W) -> (Readable[C, S], W) {
        var { cap: c, bytes: s } = value;
        let o = out.write(&c, s);
        (Readable.{ cap: c, bytes: s }, o)
    }
}

/// A writer that also carries a context that reads a domain's bytes
/// (`ReadBytes`), so an f-string can interpolate text of that domain directly:
/// every `{text}` is read through the writer's own context, one context
/// serving any number of parts. `finish` hands both back. `f"...".write(&cx,
/// out)` is written through one, the context moved out of `cx` and put back:
///
///     let text = f"{name} = {value}".write(&cx, Buffer!::new());
forall W, C.
exposed struct ReadingWriter! {
    out: W,
    cx: C,
}

forall W, C.
impl ReadingWriter![W, C] {
    /// A writer to `out` that reads text through `cx`.
    fn new(out: W, cx: C) -> ReadingWriter![W, C] {
        ReadingWriter!.{ out, cx }
    }

    /// Ends the session, handing back the inner writer and the context.
    fn finish(self) -> (W, C) {
        let { out, cx } = self;
        (out, cx)
    }
}

/// Every write goes to the inner writer.
forall W, C where Writer[W].
instance Writer[ReadingWriter![W, C]] {
    fn write_byte(self: ReadingWriter![W, C], byte: u8) -> ReadingWriter![W, C] {
        let { out, ..rest } = self;
        ReadingWriter!.{ out: Writer[W]::write_byte(out, byte), ..rest }
    }
    fn write_static(self: ReadingWriter![W, C], bytes: Str['static]) -> ReadingWriter![W, C] {
        let { out, ..rest } = self;
        ReadingWriter!.{ out: Writer[W]::write_static(out, bytes), ..rest }
    }
    /// Caller: as for `Writer::write_raw`, `ptr[0..len)` is readable for the
    /// whole call.
    unsafe fn write_raw(self: ReadingWriter![W, C], ptr: *u8, len: usize) -> ReadingWriter![W, C] {
        let { out, ..rest } = self;
        ReadingWriter!.{ out: unsafe Writer[W]::write_raw(out, ptr, len), ..rest }
    }
}

/// Text formats as its bytes, read through the writer's context:
/// `f"{name}".write(&cx, out)` with `name: Str['k]`. A `Str['static]` in an
/// f-string is written directly, as literal text is.
forall W, C, 'r where Writer[W], ReadBytes[C, Str['r]].
instance Format[Str['r], ReadingWriter![W, C]] {
    fn format(value: Str['r], out: ReadingWriter![W, C]) -> (Str['r], ReadingWriter![W, C]) {
        var { out: o, cx } = out;
        let o2 = o.write(&cx, value);
        (value, ReadingWriter!.{ out: o2, cx })
    }
}

/// Counts bytes without storing them.
exposed struct CountingWriter {
    count: usize,
}

impl CountingWriter {
    /// A writer that has counted nothing yet.
    fn new() -> CountingWriter {
        CountingWriter.{ count: 0usize }
    }
}

/// Each write adds its length to the count.
instance Writer[CountingWriter] {
    fn write_byte(self: CountingWriter, byte: u8) -> CountingWriter {
        let { count } = self;
        CountingWriter.{ count: count + 1usize }
    }
    fn write_static(self: CountingWriter, bytes: Str['static]) -> CountingWriter {
        let { count } = self;
        CountingWriter.{ count: count + bytes.len() }
    }
    /// Caller: as for `Writer::write_raw`, `ptr[0..len)` is readable for the
    /// whole call.
    unsafe fn write_raw(self: CountingWriter, ptr: *u8, len: usize) -> CountingWriter {
        let { count } = self;
        CountingWriter.{ count: count + len }
    }
}