1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use super::XlsxError;
use std::error::Error;
use std::ffi;
use std::fmt::{self, Display};

#[derive(Debug, Clone, PartialEq)]
pub(crate) enum XlsxErrorSource {
    LibXlsxWriter(libxlsxwriter_sys::lxw_error),
    NumberOfColumnsIsNotMatched,
    Unknown,
    NulError(std::ffi::NulError),
}

impl Error for XlsxError {}

impl XlsxError {
    pub(crate) fn new(error: libxlsxwriter_sys::lxw_error) -> XlsxError {
        XlsxError {
            source: XlsxErrorSource::LibXlsxWriter(error),
        }
    }

    pub(crate) fn unknown_error() -> XlsxError {
        XlsxError {
            source: XlsxErrorSource::Unknown,
        }
    }
}

impl Display for XlsxError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.source {
            XlsxErrorSource::Unknown => {
                write!(f, "Unknown Error")
            }
            XlsxErrorSource::NumberOfColumnsIsNotMatched => {
                write!(
                    f,
                    "Number of columns in an option is not equal to table size"
                )
            }
            XlsxErrorSource::NulError(e) => {
                write!(f, "Null bytes in string: {}", e)
            }
            XlsxErrorSource::LibXlsxWriter(error) => unsafe {
                match ffi::CStr::from_ptr(libxlsxwriter_sys::lxw_strerror(*error)).to_str() {
                    Ok(error_text) => write!(f, "{}", error_text),
                    Err(e) => write!(f, "Cannot get xlsx error text: {}", e),
                }
            },
        }
    }
}

impl From<std::ffi::NulError> for XlsxError {
    fn from(e: std::ffi::NulError) -> Self {
        XlsxError {
            source: XlsxErrorSource::NulError(e),
        }
    }
}