silcrow 0.2.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
//! Standard output, held per thread while one project of several runs beside the others, so
//! each project's lines print together and in project order.

use std::cell::RefCell;
use std::fmt::Arguments;
use std::io::Write;

thread_local! {
    static HELD: RefCell<Option<Vec<u8>>> = const { RefCell::new(None) };
}

/// Writes `args` and a newline to standard output, or to what this thread holds.
pub fn line(args: Arguments<'_>) {
    let held = HELD.with(|held| {
        let mut held = held.borrow_mut();
        let buffer = held.as_mut()?;
        let _ = writeln!(buffer, "{args}");
        Some(())
    });
    if held.is_none() {
        println!("{args}");
    }
}

/// Runs `f` with this thread's standard output held, and returns what it wrote.
pub fn held<T>(f: impl FnOnce() -> T) -> (T, Vec<u8>) {
    HELD.with(|held| *held.borrow_mut() = Some(Vec::new()));
    let value = f();
    let written = HELD
        .with(|held| held.borrow_mut().take())
        .unwrap_or_default();
    (value, written)
}

/// Writes what a thread held to standard output.
pub fn release(written: &[u8]) {
    let mut stdout = std::io::stdout().lock();
    if let Err(e) = stdout.write_all(written) {
        // The words `println!` panics with, which a closed pipe exits quietly on.
        panic!("failed printing to stdout: {e}");
    }
}

/// `println!` through `out::line`.
#[macro_export]
macro_rules! say {
    () => {
        $crate::out::line(format_args!(""))
    };
    ($($arg:tt)*) => {
        $crate::out::line(format_args!($($arg)*))
    };
}