tabnas-dmog 0.4.0

The dmog library and command (data mogrify): translates a document from any tabnas format into any other, streaming, and runs alchemy programs over JSON documents, composing tabnas-alchemy, tabnas-transduce and tabnas-render.
Documentation
//! The thread every call that compiles or runs a program takes, how a run
//! is stopped, and the text a run over a string writes.

use std::io::Write;
use std::sync::{Arc, Mutex, PoisonError};

use tabnas_transduce::{AbortFlag, Code, Fail};

use crate::translate;

/// A handle that stops a run: [`Abort::abort`] makes every run given it
/// (`run_with_abort`) fail with [`Code::Aborted`]. A run checks it between
/// parse steps and as its program's functions run, and one given an
/// aborted handle fails before it starts. Clones share one state, so a
/// clone can be moved to the thread that decides to stop.
#[derive(Clone, Debug, Default)]
pub struct Abort(AbortFlag);

impl Abort {
    pub fn new() -> Abort {
        Abort::default()
    }

    pub fn abort(&self) {
        self.0.abort();
    }

    pub fn is_aborted(&self) -> bool {
        self.0.is_aborted()
    }
}

/// `work` on a thread of [`tabnas_alchemy::STACK_BYTES`], the stack the
/// checker and the evaluator are promised.
pub(crate) fn on_stack<T: Send>(work: impl FnOnce() -> Result<T, Fail> + Send) -> Result<T, Fail> {
    std::thread::scope(|scope| {
        std::thread::Builder::new()
            .name("dmog".into())
            .stack_size(tabnas_alchemy::STACK_BYTES)
            .spawn_scoped(scope, work)
            .map_err(|error| {
                Fail::new(
                    Code::ResourceLimitExceeded,
                    format!("no thread could be started for the run: {error}"),
                )
            })?
            .join()
            .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
    })
}

/// One run on its own thread, stopped by `abort`. Input that cannot be
/// read fails as `unreadable: ` and the reason, by whichever route the
/// run read it.
pub(crate) fn run_on_stack(
    abort: &Abort,
    run: impl FnOnce(&AbortFlag) -> Result<(), Fail> + Send,
) -> Result<(), Fail> {
    if abort.is_aborted() {
        return Err(Fail::aborted());
    }
    on_stack(|| run(&abort.0)).map_err(|mut fail| {
        if let Some(reason) = translate::unreadable(&fail).map(str::to_owned) {
            fail.message = format!("unreadable: {reason}");
        }
        fail
    })
}

/// What a run over a string writes, kept for the caller.
#[derive(Clone, Default)]
pub(crate) struct Written(Arc<Mutex<Vec<u8>>>);

impl Written {
    pub(crate) fn text(&self) -> Result<String, Fail> {
        let bytes = std::mem::take(&mut *self.0.lock().unwrap_or_else(PoisonError::into_inner));
        String::from_utf8(bytes).map_err(|_| Fail::output("the output is not UTF-8"))
    }
}

impl Write for Written {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        self.0
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .extend_from_slice(bytes);
        Ok(bytes.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}