1use std::fmt;
4
5pub type Result<T> = std::result::Result<T, Error>;
7
8#[derive(Debug, Clone, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum Error {
12 InvalidDimensions {
14 width: u32,
16 height: u32,
18 },
19 BufferSizeMismatch {
21 expected: usize,
23 actual: usize,
25 },
26 InvalidQuality(u8),
28 InvalidQuantTableIndex(usize),
30 InvalidComponentIndex(usize),
32 InvalidHuffmanTableIndex(usize),
34 InvalidSamplingFactor {
36 h: u8,
38 v: u8,
40 },
41 InvalidScanSpec {
43 reason: &'static str,
45 },
46 InvalidHuffmanTable,
48 HuffmanCodeLengthOverflow,
50 UnsupportedColorSpace,
52 UnsupportedFeature(&'static str),
54 InternalError(&'static str),
56 IoError(String),
58 AllocationFailed,
60}
61
62impl fmt::Display for Error {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 match self {
65 Error::InvalidDimensions { width, height } => {
66 write!(f, "Invalid image dimensions: {}x{}", width, height)
67 }
68 Error::BufferSizeMismatch { expected, actual } => {
69 write!(
70 f,
71 "Buffer size mismatch: expected {}, got {}",
72 expected, actual
73 )
74 }
75 Error::InvalidQuality(q) => {
76 write!(f, "Invalid quality value: {} (must be 1-100)", q)
77 }
78 Error::InvalidQuantTableIndex(idx) => {
79 write!(f, "Invalid quantization table index: {}", idx)
80 }
81 Error::InvalidComponentIndex(idx) => {
82 write!(f, "Invalid component index: {}", idx)
83 }
84 Error::InvalidHuffmanTableIndex(idx) => {
85 write!(f, "Invalid Huffman table index: {}", idx)
86 }
87 Error::InvalidSamplingFactor { h, v } => {
88 write!(f, "Invalid sampling factor: {}x{}", h, v)
89 }
90 Error::InvalidScanSpec { reason } => {
91 write!(f, "Invalid scan specification: {}", reason)
92 }
93 Error::InvalidHuffmanTable => {
94 write!(f, "Invalid Huffman table structure")
95 }
96 Error::HuffmanCodeLengthOverflow => {
97 write!(f, "Huffman code length overflow (exceeds 16 bits)")
98 }
99 Error::UnsupportedColorSpace => {
100 write!(f, "Unsupported color space")
101 }
102 Error::UnsupportedFeature(feature) => {
103 write!(f, "Unsupported feature: {}", feature)
104 }
105 Error::InternalError(msg) => {
106 write!(f, "Internal encoder error: {}", msg)
107 }
108 Error::IoError(msg) => {
109 write!(f, "I/O error: {}", msg)
110 }
111 Error::AllocationFailed => {
112 write!(f, "Memory allocation failed")
113 }
114 }
115 }
116}
117
118impl std::error::Error for Error {}
119
120impl From<std::io::Error> for Error {
121 fn from(e: std::io::Error) -> Self {
122 Error::IoError(e.to_string())
123 }
124}
125
126impl From<std::collections::TryReserveError> for Error {
127 fn from(_: std::collections::TryReserveError) -> Self {
128 Error::AllocationFailed
129 }
130}