← alloc

alloc/fmt.kur

//! Formatting adapters for owning byte buffers.
// alloc::fmt -- writers, printing and formatting. Re-exports `core::fmt`'s
// allocator-free protocol and adds what needs `Buffer!`: its `Format` and
// `Printable` instances, and `FixedWriter!`. `f"..."` expands through the
// `Writer` and `Format` names exported here. `Buffer!`'s own `Writer`
// instance is in `alloc::buffer`, beside its fields.

use package as alloc;

use core::fmt::{Writer, Format, Printable, ReadingWriter!, CountingWriter};
export Writer;
export Format;
export Printable;
export ReadingWriter!;
export CountingWriter;
use core::str::{Str, StaticRead};
use core::raw::raw_byte_at;
use core::option::Result;
use alloc::buffer::Buffer!;

/// Formats an owned buffer as its contents. The buffer is handed back, not
/// freed: an f-string formats a linear value only through `{&name}`.
forall W where Writer[W].
instance Format[Buffer!, W] {
    fn format(value: Buffer!, out: W) -> (Buffer!, W) {
        let exists 'b. (tag, bytes, restore) = value.open();
        // `unsafe`: the open buffer's bytes stay readable until `restore`.
        let (ptr, len, marker) = bytes.into_parts();
        let o = unsafe Writer[W]::write_raw(out, ptr, len);
        (restore.restore(tag), o)
    }
}

/// A buffer prints as its contents, and is freed.
forall W where Writer[W].
instance Printable[Buffer!, W] {
    fn print(value: Buffer!, out: W) -> W {
        var value = value;
        let p = unsafe &value.as_ptr();
        let n = &value.len();
        // `p` addresses the `n` bytes `value` holds until it is freed below.
        let o = unsafe Writer[W]::write_raw(out, p, n);
        value.destroy();
        o
    }
}

/// The sticky error a `FixedWriter!` reports once it has run out of room.
exposed struct Full {}

/// A byte buffer that never grows past `cap`. The first write that does not
/// fit marks it full; that write and every later one is dropped, so the
/// contents are always a prefix of what was written.
struct FixedWriter! {
    buf: Buffer!,
    cap: usize,
    full: bool,
}

impl FixedWriter! {
    /// An empty writer that holds at most `cap` bytes.
    fn new(cap: usize) -> FixedWriter! {
        FixedWriter!.{ buf: Buffer!::with_capacity(cap), cap, full: false }
    }

    /// The bytes written, and `Full` if any write was dropped.
    fn finish(self) -> (Buffer!, Result[(), Full]) {
        let { buf, cap, full } = self;
        let status = if full {
            Result[(), Full]::Err.(Full.{})
        } else {
            Result[(), Full]::Ok.(())
        };
        (buf, status)
    }
}

/// A fixed writer as a writer: bytes past its capacity are dropped.
instance Writer[FixedWriter!] {
    fn write_byte(self: FixedWriter!, byte: u8) -> FixedWriter! {
        var { buf, cap, full } = self;
        let n = &buf.len();
        if full || n >= cap {
            FixedWriter!.{ buf, cap, full: true }
        } else {
            FixedWriter!.{ buf: buf.write_byte(byte), cap, full }
        }
    }
    fn write_static(self: FixedWriter!, bytes: Str['static]) -> FixedWriter! {
        var sr = StaticRead::new();
        self.write(&sr, bytes)
    }
    /// Caller: as for `Writer::write_raw`, `ptr[0..len)` is readable for the
    /// whole call.
    unsafe fn write_raw(self: FixedWriter!, ptr: *u8, len: usize) -> FixedWriter! {
        var w = self;
        var i = 0usize;
        while i < len {
            w = w.write_byte(unsafe raw_byte_at(ptr, len, i));
            i = i + 1usize;
        }
        w
    }
}