Skip to main content

rfitsio/
error.rs

1//! [`FitsError`]: CFITSIO status plus an optional message stack.
2
3use std::cell::RefCell;
4use std::error::Error;
5use std::fmt;
6
7use crate::status;
8
9thread_local! {
10    static MSG_STACK: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
11}
12
13/// Push a message onto the per-thread analogue of CFITSIO's `ffpmsg` stack.
14pub fn push_err_msg(msg: impl Into<String>) {
15    MSG_STACK.with(|s| s.borrow_mut().push(msg.into()));
16}
17
18/// Pop the oldest message (`fits_read_errmsg` / `ffgmsg`).
19pub fn pop_err_msg() -> Option<String> {
20    MSG_STACK.with(|s| {
21        let mut v = s.borrow_mut();
22        if v.is_empty() {
23            None
24        } else {
25            Some(v.remove(0))
26        }
27    })
28}
29
30/// Clear the message stack (`fits_clear_errmsg` / `ffcmsg`).
31pub fn clear_err_msg() {
32    MSG_STACK.with(|s| s.borrow_mut().clear());
33}
34
35/// An error identified by a CFITSIO status code.
36///
37/// `status` is the `int` CFITSIO would have written through `int *status`.
38/// `messages` is the per-call analogue of the `ffpmsg` stack (not yet a
39/// process-global stack).
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct FitsError {
42    /// CFITSIO status code.
43    pub status: i32,
44    messages: Vec<String>,
45}
46
47impl FitsError {
48    /// Error with a status code and an empty message stack.
49    #[must_use]
50    pub fn new(status: i32) -> Self {
51        Self {
52            status,
53            messages: Vec::new(),
54        }
55    }
56
57    /// Error with a status code and one stack message.
58    #[must_use]
59    pub fn with_message(status: i32, msg: impl Into<String>) -> Self {
60        Self {
61            status,
62            messages: vec![msg.into()],
63        }
64    }
65
66    /// Short `ffgerr` text for [`Self::status`].
67    #[must_use]
68    pub fn status_text(&self) -> &'static str {
69        status::status_text(self.status)
70    }
71
72    /// Messages that would appear on CFITSIO's error stack for this call.
73    #[must_use]
74    pub fn messages(&self) -> &[String] {
75        &self.messages
76    }
77
78    /// Append a stack message (analogue of `ffpmsg`).
79    pub fn push_message(&mut self, msg: impl Into<String>) {
80        self.messages.push(msg.into());
81    }
82}
83
84impl fmt::Display for FitsError {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        write!(f, "{} ({})", self.status_text(), self.status)?;
87        for msg in &self.messages {
88            write!(f, ": {msg}")?;
89        }
90        Ok(())
91    }
92}
93
94impl Error for FitsError {}
95
96/// Alias used throughout the crate.
97pub type Result<T> = std::result::Result<T, FitsError>;