Skip to main content

phasm_core/codec/jpeg/
error.rs

1// Copyright (c) 2026 Christoph Gaffga
2// SPDX-License-Identifier: GPL-3.0-only
3// https://github.com/cgaffga/phasmcore
4
5//! Error types for JPEG parsing and encoding.
6
7use std::fmt;
8
9/// Errors that can occur during JPEG parsing or encoding.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum JpegError {
12    /// Input data is too short or truncated.
13    UnexpectedEof,
14    /// Missing SOI (0xFFD8) at start of data.
15    InvalidSoi,
16    /// Missing EOI (0xFFD9) — non-fatal for some files.
17    MissingEoi,
18    /// Encountered an unsupported JPEG marker (progressive, arithmetic, etc.).
19    UnsupportedMarker(u8),
20    /// A marker segment has invalid or inconsistent length/content.
21    InvalidMarkerData(&'static str),
22    /// Huffman decode error (invalid code encountered in scan data).
23    HuffmanDecode,
24    /// Quantization table ID out of range (0–3).
25    InvalidQuantTableId(u8),
26    /// Huffman table ID out of range or missing.
27    InvalidHuffmanTableId(u8),
28    /// Component ID referenced in SOS not found in SOF.
29    UnknownComponentId(u8),
30    /// Image dimensions or sampling factors are invalid.
31    InvalidDimensions,
32    /// 12-bit precision is not supported.
33    UnsupportedPrecision(u8),
34}
35
36impl fmt::Display for JpegError {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self {
39            Self::UnexpectedEof => write!(f, "unexpected end of JPEG data"),
40            Self::InvalidSoi => write!(f, "missing SOI marker (not a JPEG)"),
41            Self::MissingEoi => write!(f, "missing EOI marker"),
42            Self::UnsupportedMarker(m) => write!(f, "unsupported JPEG marker: 0xFF{m:02X}"),
43            Self::InvalidMarkerData(msg) => write!(f, "invalid marker data: {msg}"),
44            Self::HuffmanDecode => write!(f, "Huffman decode error"),
45            Self::InvalidQuantTableId(id) => write!(f, "invalid quantization table ID: {id}"),
46            Self::InvalidHuffmanTableId(id) => write!(f, "invalid Huffman table ID: {id}"),
47            Self::UnknownComponentId(id) => write!(f, "unknown component ID in SOS: {id}"),
48            Self::InvalidDimensions => write!(f, "invalid image dimensions or sampling factors"),
49            Self::UnsupportedPrecision(p) => write!(f, "unsupported sample precision: {p}-bit"),
50        }
51    }
52}
53
54impl std::error::Error for JpegError {}
55
56pub type Result<T> = std::result::Result<T, JpegError>;