icsneoc2 0.1002002.0-rc.4

High-level Rust interface for Intrepid Control Systems vehicle network adapters
Documentation
//! Error types for the icsneoc2 crate.
//!
//! [`Error`] wraps the various failure modes that can occur when calling
//! the underlying C library, including API-level status codes, string
//! conversion failures, and memory allocation problems.
//!
//! Most public methods in this crate return [`Result<T>`], which is an
//! alias for `std::result::Result<T, Error>`.

use crate::sys;
use std::ffi::{IntoStringError, NulError};
use std::fmt::Display;
use std::str::Utf8Error;

/// The error type for all icsneoc2 operations.
///
/// Most variants carry a human-readable description obtained from the C
/// library or from Rust's own conversion routines.
#[derive(Debug, Clone)]
pub enum Error {
    /// A C API function returned a non-success status code.
    ///
    /// The first field is the raw error variant; the second is the
    /// human-readable description returned by `icsneoc2_error_code_get`.
    APIError(sys::Error, String),
    /// The lookup of a human-readable error description itself failed.
    ErrorCodeGetError(sys::Error),
    /// Failed to convert a C string to a Rust `String`.
    StringConversionError(String),
    /// Memory allocation or null-pointer error.
    MemoryError(String),
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::APIError(error_code, error_string) => {
                write!(f, "API Error: \"{}\" ({:?})", error_string, error_code)
            }
            Error::ErrorCodeGetError(error_code) => write!(
                f,
                "Failed to get error code description for error code: {:?}",
                error_code
            ),
            Error::StringConversionError(error_string) => {
                write!(f, "String Conversion Error: \"{}\"", error_string)
            }
            Error::MemoryError(error_string) => {
                write!(f, "Memory Error: \"{}\"", error_string)
            }
        }
    }
}

impl From<Utf8Error> for Error {
    fn from(error: Utf8Error) -> Self {
        Error::StringConversionError(format!("UTF-8 conversion error: {}", error))
    }
}

impl From<NulError> for Error {
    fn from(error: NulError) -> Self {
        Error::StringConversionError(format!("Nul byte found in string: {}", error))
    }
}

impl From<IntoStringError> for Error {
    fn from(error: IntoStringError) -> Self {
        Error::StringConversionError(format!("Failed to convert CString to String: {}", error))
    }
}

impl From<sys::InvalidEnumValue> for Error {
    fn from(error: sys::InvalidEnumValue) -> Self {
        Error::StringConversionError(format!("{}", error))
    }
}

impl std::error::Error for Error {}

pub type Result<T> = core::result::Result<T, Error>;