use std::{error, ffi::NulError, fmt};
use crate::raw;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
Nul(NulError),
Null(&'static str),
Glib(GlibError),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GlibError {
pub domain: u32,
pub code: i32,
pub message: String,
}
impl Error {
pub(crate) fn glib(error: *mut libcogcore_sys::GError) -> Self {
Self::Glib(raw::take_gerror(error))
}
}
impl From<NulError> for Error {
fn from(error: NulError) -> Self {
Self::Nul(error)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Nul(error) => write!(f, "string contains an interior NUL byte: {error}"),
Self::Null(context) => write!(f, "{context} returned a null pointer"),
Self::Glib(error) => write!(
f,
"GLib error domain={} code={}: {}",
error.domain, error.code, error.message
),
}
}
}
impl error::Error for Error {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display_mentions_null_context() {
let message = Error::Null("cog_platform_get").to_string();
assert!(message.contains("cog_platform_get"));
}
}