binparse 0.1.0

A colorful, user-friendly alternative to readelf for analyzing ELF binaries
//! Custom error types for binparse.
//!
//! Provides structured error handling with descriptive messages
//! for all possible failure modes when parsing binary files.

use std::path::PathBuf;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum BinparseError {
    /// Failed to read the input file
    #[error("Failed to read file '{path}': {source}")]
    FileRead {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Not a valid ELF file: {0}")]
    NotElf(String),

    /// Failed to parse the binary format
    #[error("Failed to parse binary: {0}")]
    ParseError(String),

    /// The binary format is not supported
    #[error("Unsupported binary format: {0}")]
    UnsupportedFormat(String),

    /// The file is empty or too small
    #[error("File is too small to be a valid binary ({size} bytes)")]
    FileTooSmall { size: usize },

    /// Section or segment not found
    #[error("{kind} not found: {name}")]
    NotFound { kind: &'static str, name: String },

    /// String table access error
    #[error("Failed to read string from string table at offset {offset}")]
    StringTableError { offset: usize },
}

impl From<goblin::error::Error> for BinparseError {
    fn from(err: goblin::error::Error) -> Self {
        match err {
            goblin::error::Error::Malformed(msg) => BinparseError::ParseError(msg.to_string()),
            goblin::error::Error::BadMagic(magic) => {
                BinparseError::NotElf(format!("Bad magic number: 0x{:08X}", magic))
            }
            goblin::error::Error::Scroll(e) => BinparseError::ParseError(e.to_string()),
            goblin::error::Error::IO(e) => BinparseError::ParseError(e.to_string()),
            goblin::error::Error::BufferTooShort(needed, _) => {
                BinparseError::ParseError(format!("Buffer too short, needed {} bytes", needed))
            }
            _ => BinparseError::ParseError(err.to_string()),
        }
    }
}

pub type Result<T> = std::result::Result<T, BinparseError>;