cge_nes 0.1.0

Cycle-accurate NES (Nintendo Entertainment System) emulator library: CPU, PPU, cartridge, input, and iNES ROM loading.
Documentation
//! Error types for ROM loading and parsing operations.
//!
//! This module provides a custom error type [`RomError`] that encapsulates
//! various failure modes that can occur when working with NES ROM files.
//! It handles both I/O errors from file operations and format validation
//! errors specific to the iNES format.
//!
//! # Error Categories
//!
//! * I/O Errors - Failures during file operations (read, seek, etc.)
//! * Format Errors - Invalid ROM format, unsupported mappers, etc.
//!
//! # Examples
//!
//! ```
//! use cge_nes::rom_loader::RomError;
//!
//! // Creating a format error
//! let format_error = RomError::RomFormat("Invalid NES header magic number".to_string());
//!
//! // Converting an IO error
//! let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "File not found");
//! let rom_error = RomError::from(io_error);
//! ```

use std::{error, fmt, io};

/// Represents errors that can occur during ROM loading and parsing operations.
///
/// This enum encapsulates different types of errors that might occur when working
/// with NES ROM files, including I/O errors and format validation errors.
#[derive(Debug)]
pub enum RomError {
    /// Represents errors related to file I/O operations.
    ///
    /// This variant wraps a standard `io::Error` and is used when file operations
    /// like reading or seeking fail.
    Io(io::Error),

    /// Represents errors related to ROM file format validation.
    ///
    /// This variant is used when the ROM file doesn't conform to the expected iNES format,
    /// such as invalid headers, wrong magic numbers, or unsupported mapper types.
    ///
    /// # Examples
    /// - Missing NES magic constant
    /// - Invalid PRG/CHR ROM sizes
    /// - Unsupported mapper numbers
    RomFormat(String),

    /// Mapper number was recognised as a valid iNES value but no
    /// implementation is compiled in for it. Carries the mapper id.
    UnsupportedMapper(u8),
}

impl From<io::Error> for RomError {
    fn from(value: io::Error) -> Self {
        Self::Io(value)
    }
}

impl fmt::Display for RomError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RomError::RomFormat(msg) => write!(f, "{msg}"),
            RomError::Io(io_error) => write!(f, "{io_error}"),
            RomError::UnsupportedMapper(mapper) => {
                write!(f, "unsupported mapper: {mapper:03} (not implemented)")
            }
        }
    }
}

impl error::Error for RomError {}