use std::cell::RefCell;
use std::error::Error;
use std::fmt;
use crate::status;
thread_local! {
static MSG_STACK: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
pub fn push_err_msg(msg: impl Into<String>) {
MSG_STACK.with(|s| s.borrow_mut().push(msg.into()));
}
pub fn pop_err_msg() -> Option<String> {
MSG_STACK.with(|s| {
let mut v = s.borrow_mut();
if v.is_empty() {
None
} else {
Some(v.remove(0))
}
})
}
pub fn clear_err_msg() {
MSG_STACK.with(|s| s.borrow_mut().clear());
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FitsError {
pub status: i32,
messages: Vec<String>,
}
impl FitsError {
#[must_use]
pub fn new(status: i32) -> Self {
Self {
status,
messages: Vec::new(),
}
}
#[must_use]
pub fn with_message(status: i32, msg: impl Into<String>) -> Self {
Self {
status,
messages: vec![msg.into()],
}
}
#[must_use]
pub fn status_text(&self) -> &'static str {
status::status_text(self.status)
}
#[must_use]
pub fn messages(&self) -> &[String] {
&self.messages
}
pub fn push_message(&mut self, msg: impl Into<String>) {
self.messages.push(msg.into());
}
}
impl fmt::Display for FitsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ({})", self.status_text(), self.status)?;
for msg in &self.messages {
write!(f, ": {msg}")?;
}
Ok(())
}
}
impl Error for FitsError {}
pub type Result<T> = std::result::Result<T, FitsError>;