use crate::ffi;
use std::error;
use std::ffi::CStr;
use std::fmt;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Error {
code: Option<i32>,
message: String,
}
impl Error {
pub fn new(message: impl Into<String>) -> Self {
Self {
code: None,
message: message.into(),
}
}
pub(crate) fn from_device(device: *mut ffi::nfc_device, code: i32) -> Self {
let message = if device.is_null() {
format!("libnfc error code {code}")
} else {
unsafe { CStr::from_ptr(ffi::nfc_strerror(device)).to_string_lossy().into_owned() }
};
Self {
code: Some(code),
message,
}
}
pub fn code(&self) -> Option<i32> {
self.code
}
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.code {
Some(code) => write!(f, "{} ({code})", self.message),
None => f.write_str(&self.message),
}
}
}
impl error::Error for Error {}