use std::cell::RefCell;
use std::marker::PhantomData;
use std::rc::Rc;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Captured {
pub text: String,
pub warning: bool,
}
thread_local! {
static CAPTURE: RefCell<Option<Vec<Captured>>> = const { RefCell::new(None) };
}
#[derive(Debug)]
pub struct PrintCapture {
saved: Option<Vec<Captured>>,
_thread: PhantomData<Rc<()>>,
}
impl PrintCapture {
#[must_use]
pub fn start() -> Self {
let saved = CAPTURE.with(|c| c.borrow_mut().replace(Vec::new()));
Self {
saved,
_thread: PhantomData,
}
}
#[must_use]
pub fn take(&self) -> Vec<Captured> {
CAPTURE.with(|c| {
c.borrow_mut()
.as_mut()
.map(std::mem::take)
.unwrap_or_default()
})
}
}
impl Drop for PrintCapture {
fn drop(&mut self) {
let saved = self.saved.take();
CAPTURE.with(|c| *c.borrow_mut() = saved);
}
}
pub(crate) fn push(text: String, warning: bool) -> Option<String> {
CAPTURE.with(|c| match c.borrow_mut().as_mut() {
Some(lines) => {
lines.push(Captured { text, warning });
None
}
None => Some(text),
})
}
pub(crate) fn active() -> bool {
CAPTURE.with(|c| c.borrow().is_some())
}