use std::cell::RefCell;
use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PipelineError(pub String);
impl PipelineError {
pub fn new(message: impl Into<String>) -> Self {
PipelineError(message.into())
}
}
impl fmt::Display for PipelineError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for PipelineError {}
thread_local! {
static CAPTURES: RefCell<Vec<Option<PipelineError>>> = const { RefCell::new(Vec::new()) };
}
struct Frame;
impl Drop for Frame {
fn drop(&mut self) {
CAPTURES.with(|c| c.borrow_mut().pop());
}
}
pub fn capture<T>(body: impl FnOnce() -> T) -> Result<T, PipelineError> {
CAPTURES.with(|c| c.borrow_mut().push(None));
let frame = Frame;
let result = body();
let error = CAPTURES.with(|c| c.borrow_mut().last_mut().and_then(Option::take));
drop(frame);
match error {
Some(e) => Err(e),
None => Ok(result),
}
}
pub fn has_failed() -> bool {
CAPTURES.with(|c| matches!(c.borrow().last(), Some(Some(_))))
}
pub fn report(message: impl Into<String>) {
let message = message.into();
CAPTURES.with(|c| match c.borrow_mut().last_mut() {
Some(slot) => {
if slot.is_none() {
*slot = Some(PipelineError(message));
}
}
None => eprintln!("zero-client: pipeline error: {message}"),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_innermost_capture_gets_the_first_report() {
let outer = capture(|| {
let inner = capture(|| {
report("a");
report("b");
assert!(has_failed());
});
assert_eq!(inner, Err(PipelineError::new("a")));
assert!(!has_failed());
});
assert_eq!(outer, Ok(()));
}
}