use std::io::Write;
use std::sync::{Arc, Mutex, PoisonError};
use tabnas_transduce::{AbortFlag, Code, Fail};
use crate::translate;
#[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()
}
}
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))
})
}
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
})
}
#[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(())
}
}