zero_client/ivm/
failure.rs1use std::cell::RefCell;
10use std::fmt;
11
12#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct PipelineError(pub String);
15
16impl PipelineError {
17 pub fn new(message: impl Into<String>) -> Self {
18 PipelineError(message.into())
19 }
20}
21
22impl fmt::Display for PipelineError {
23 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24 f.write_str(&self.0)
25 }
26}
27
28impl std::error::Error for PipelineError {}
29
30thread_local! {
31 static CAPTURES: RefCell<Vec<Option<PipelineError>>> = const { RefCell::new(Vec::new()) };
34}
35
36struct Frame;
37
38impl Drop for Frame {
39 fn drop(&mut self) {
40 CAPTURES.with(|c| c.borrow_mut().pop());
41 }
42}
43
44pub fn capture<T>(body: impl FnOnce() -> T) -> Result<T, PipelineError> {
47 CAPTURES.with(|c| c.borrow_mut().push(None));
48 let frame = Frame;
49 let result = body();
50 let error = CAPTURES.with(|c| c.borrow_mut().last_mut().and_then(Option::take));
51 drop(frame);
52 match error {
53 Some(e) => Err(e),
54 None => Ok(result),
55 }
56}
57
58pub fn has_failed() -> bool {
61 CAPTURES.with(|c| matches!(c.borrow().last(), Some(Some(_))))
62}
63
64pub fn report(message: impl Into<String>) {
68 let message = message.into();
69 CAPTURES.with(|c| match c.borrow_mut().last_mut() {
70 Some(slot) => {
71 if slot.is_none() {
72 *slot = Some(PipelineError(message));
73 }
74 }
75 None => eprintln!("zero-client: pipeline error: {message}"),
76 })
77}
78
79#[cfg(test)]
80mod tests {
81 use super::*;
82
83 #[test]
84 fn the_innermost_capture_gets_the_first_report() {
85 let outer = capture(|| {
86 let inner = capture(|| {
87 report("a");
88 report("b");
89 assert!(has_failed());
90 });
91 assert_eq!(inner, Err(PipelineError::new("a")));
92 assert!(!has_failed());
93 });
94 assert_eq!(outer, Ok(()));
95 }
96}