Skip to main content

edid_seria/
error.rs

1//! Structured errors for strict EDID parsing and validation.
2
3use std::fmt;
4
5/// Errors returned when an EDID block cannot be accepted by the strict parser.
6#[derive(Clone, Debug, PartialEq, Eq)]
7#[non_exhaustive]
8pub enum EdidError {
9    /// The input is not exactly one complete EDID block.
10    InvalidLength {
11        /// Required EDID block length.
12        expected: usize,
13        /// Actual input length.
14        actual: usize,
15    },
16    /// A base block does not begin with the required EDID header.
17    InvalidHeader,
18    /// The block bytes do not sum to zero modulo 256.
19    InvalidChecksum {
20        /// Sum of all block bytes modulo 256.
21        sum: u8,
22    },
23    /// The input is not a whole sequence of EDID blocks.
24    InvalidBlockSequenceLength {
25        /// Actual input length in bytes.
26        actual: usize,
27    },
28    /// The base block's extension count disagrees with the supplied blocks.
29    ExtensionCountMismatch {
30        /// Count declared by the base block.
31        declared: usize,
32        /// Number of extension blocks supplied.
33        actual: usize,
34    },
35    /// An extension index is outside the current extension list.
36    ExtensionIndexOutOfRange {
37        /// Requested zero-based extension index.
38        index: usize,
39        /// Current extension count.
40        count: usize,
41    },
42    /// The extension count cannot be represented by the base block byte.
43    TooManyExtensions {
44        /// Requested extension count.
45        count: usize,
46    },
47    /// The base block uses an unsupported EDID version.
48    UnsupportedVersion {
49        /// EDID major version.
50        major: u8,
51        /// EDID minor version.
52        minor: u8,
53    },
54}
55
56/// Errors returned while decoding or encoding base-block metadata.
57#[derive(Clone, Debug, PartialEq, Eq)]
58#[non_exhaustive]
59pub enum MetadataError {
60    /// The block does not contain the EDID base-block header.
61    NotBaseBlock,
62    /// Manufacturer ID contains a value outside A-Z.
63    InvalidManufacturerId,
64    /// Manufacturer ID contains a non-uppercase ASCII character.
65    InvalidManufacturerCharacter {
66        /// Character position in the three-letter ID.
67        index: usize,
68        /// Invalid character value.
69        character: char,
70    },
71    /// Manufacture year cannot be represented by the EDID year offset.
72    InvalidManufactureYear {
73        /// Supplied absolute year.
74        year: u16,
75    },
76    /// Manufacture week uses a reserved EDID encoding.
77    InvalidManufactureWeek {
78        /// Supplied EDID manufacture-week byte.
79        week: u8,
80    },
81    /// Gamma is outside the EDID representable range, in hundredths.
82    InvalidGamma {
83        /// Supplied gamma multiplied by 100.
84        value: u16,
85    },
86}
87impl fmt::Display for MetadataError {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        match self {
90            Self::NotBaseBlock => f.write_str("block is not an EDID base block"),
91            Self::InvalidManufacturerId => f.write_str("invalid EDID manufacturer ID"),
92            Self::InvalidManufacturerCharacter { index, character } => {
93                write!(
94                    f,
95                    "invalid manufacturer character {character:?} at index {index}"
96                )
97            }
98            Self::InvalidManufactureYear { year } => {
99                write!(f, "manufacture year {year} is outside the EDID range")
100            }
101            Self::InvalidManufactureWeek { week } => {
102                write!(f, "manufacture week {week} uses a reserved EDID encoding")
103            }
104            Self::InvalidGamma { value } => {
105                write!(f, "gamma value {value} is outside the EDID range")
106            }
107        }
108    }
109}
110
111impl std::error::Error for MetadataError {}
112
113/// Errors returned while encoding the newly added base-block metadata views.
114///
115/// This is separate from [`MetadataError`] so existing exhaustive matches on
116/// that public 0.1 enum remain source-compatible.
117#[derive(Clone, Debug, PartialEq, Eq)]
118#[non_exhaustive]
119pub enum MetadataWriteError {
120    /// The block does not contain the EDID base-block header.
121    NotBaseBlock,
122    /// A chromaticity coordinate exceeds its 10-bit EDID representation.
123    InvalidChromaticityValue {
124        /// Supplied encoded coordinate value.
125        value: u16,
126    },
127    /// A standard timing cannot be represented by its two-byte encoding.
128    InvalidStandardTiming {
129        /// Supplied horizontal active size.
130        horizontal_pixels: u16,
131        /// Supplied refresh rate.
132        refresh_rate_hz: u8,
133    },
134    /// A standard timing collides with the EDID unused-slot encoding.
135    ReservedStandardTimingEncoding,
136    /// A reserved standard-timing entry contains a valid mode encoding.
137    InvalidReservedStandardTimingEncoding {
138        /// Original two-byte encoding.
139        raw: [u8; 2],
140    },
141}
142
143impl fmt::Display for MetadataWriteError {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        match self {
146            Self::NotBaseBlock => f.write_str("block is not an EDID base block"),
147            Self::InvalidChromaticityValue { value } => {
148                write!(
149                    f,
150                    "chromaticity value {value} exceeds the 10-bit EDID range"
151                )
152            }
153            Self::InvalidStandardTiming {
154                horizontal_pixels,
155                refresh_rate_hz,
156            } => write!(
157                f,
158                "standard timing {horizontal_pixels} pixels at {refresh_rate_hz} Hz is not representable"
159            ),
160            Self::ReservedStandardTimingEncoding => {
161                f.write_str("standard timing collides with the EDID unused-slot encoding")
162            }
163            Self::InvalidReservedStandardTimingEncoding { raw } => write!(
164                f,
165                "reserved standard timing encoding {raw:02X?} is a valid mode encoding"
166            ),
167        }
168    }
169}
170
171impl std::error::Error for MetadataWriteError {}
172
173/// Errors returned while decoding or encoding monitor descriptors.
174#[derive(Clone, Debug, PartialEq, Eq)]
175#[non_exhaustive]
176pub enum DescriptorError {
177    /// The requested descriptor slot does not exist.
178    SlotOutOfRange {
179        /// Requested slot index.
180        slot: usize,
181        /// Number of descriptor slots.
182        slots: usize,
183    },
184    /// The block does not contain the EDID base-block header.
185    NotBaseBlock,
186    /// Text is longer than the 13-byte descriptor payload.
187    TextTooLong {
188        /// Maximum text length in bytes.
189        max: usize,
190        /// Supplied text length in bytes.
191        actual: usize,
192    },
193    /// Text contains a character that cannot be encoded in an EDID descriptor.
194    NonAsciiText,
195    /// A range-limit field is outside its one-byte EDID representation.
196    RangeOutOfBounds,
197    /// Chromaticity coordinate exceeds 10-bit range (0..=1023).
198    InvalidChromaticityCoordinate {
199        /// Coordinate value.
200        value: u16,
201    },
202    /// Gamma is outside the EDID representable range, in hundredths.
203    InvalidGamma {
204        /// Supplied gamma multiplied by 100.
205        value: u16,
206    },
207    /// Standard timing error in descriptor 0xFA.
208    StandardTimingError(MetadataWriteError),
209    /// Invalid descriptor revision number.
210    InvalidRevision {
211        /// Descriptor tag byte.
212        tag: u8,
213        /// Found revision byte.
214        revision: u8,
215    },
216    /// Invalid Range Limits extension definition code or parameters.
217    InvalidRangeExtension,
218    /// Invalid CVT 3-byte timing code entry.
219    InvalidCvtTiming {
220        /// CVT slot index (0..4).
221        slot: usize,
222        /// Detailed reason.
223        reason: &'static str,
224    },
225}
226impl fmt::Display for DescriptorError {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        match self {
229            Self::SlotOutOfRange { slot, slots } => {
230                write!(
231                    f,
232                    "descriptor slot {slot} is out of range ({} slots)",
233                    slots
234                )
235            }
236            Self::NotBaseBlock => f.write_str("block is not an EDID base block"),
237            Self::TextTooLong { max, actual } => {
238                write!(f, "descriptor text is {actual} bytes, maximum is {max}")
239            }
240            Self::NonAsciiText => f.write_str("descriptor text must be ASCII"),
241            Self::RangeOutOfBounds => f.write_str("descriptor range field is out of bounds"),
242            Self::InvalidChromaticityCoordinate { value } => {
243                write!(
244                    f,
245                    "descriptor chromaticity coordinate {value} exceeds 10 bits"
246                )
247            }
248            Self::InvalidGamma { value } => {
249                write!(
250                    f,
251                    "descriptor gamma value {value} is outside the EDID range"
252                )
253            }
254            Self::StandardTimingError(err) => write!(f, "descriptor standard timing error: {err}"),
255            Self::InvalidRevision { tag, revision } => {
256                write!(
257                    f,
258                    "invalid revision {revision:#04X} for descriptor tag {tag:#04X}"
259                )
260            }
261            Self::InvalidRangeExtension => f.write_str("invalid range limits extension parameters"),
262            Self::InvalidCvtTiming { slot, reason } => {
263                write!(f, "invalid CVT 3-byte timing at slot {slot}: {reason}")
264            }
265        }
266    }
267}
268
269impl std::error::Error for DescriptorError {}
270
271/// DTD field that failed a representability check.
272#[derive(Clone, Copy, Debug, PartialEq, Eq)]
273pub enum DtdField {
274    /// Horizontal active pixels.
275    HorizontalActive,
276    /// Vertical active lines.
277    VerticalActive,
278    /// Horizontal blanking pixels.
279    HorizontalBlanking,
280    /// Vertical blanking lines.
281    VerticalBlanking,
282    /// Horizontal front porch pixels.
283    HorizontalFrontPorch,
284    /// Horizontal sync width in pixels.
285    HorizontalSync,
286    /// Vertical front porch lines.
287    VerticalFrontPorch,
288    /// Vertical sync width in lines.
289    VerticalSync,
290    /// Horizontal border pixels.
291    HorizontalBorder,
292    /// Vertical border lines.
293    VerticalBorder,
294    /// Pixel clock in kHz.
295    PixelClockKHz,
296}
297
298/// Errors returned when a timing cannot be represented by an EDID DTD.
299#[derive(Clone, Debug, PartialEq, Eq)]
300#[non_exhaustive]
301pub enum DtdError {
302    /// The requested DTD slot does not exist.
303    SlotOutOfRange {
304        /// Requested slot index.
305        slot: usize,
306        /// Number of available DTD slots.
307        slots: usize,
308    },
309    /// A field has an invalid value even though it fits its bit width.
310    InvalidField {
311        /// Field with the invalid value.
312        field: DtdField,
313        /// Supplied field value.
314        value: u32,
315    },
316    /// A field exceeds its EDID bit-field limit.
317    FieldOutOfRange {
318        /// Field that exceeded its limit.
319        field: DtdField,
320        /// Supplied field value.
321        value: u32,
322        /// Largest representable field value.
323        max: u32,
324    },
325    /// An intermediate timing calculation overflowed.
326    ArithmeticOverflow,
327    /// The block has fewer reusable DTD slots than requested timings.
328    NoAvailableSlot {
329        /// Number of requested timings.
330        requested: usize,
331        /// Number of reusable slots.
332        available: usize,
333    },
334}
335impl fmt::Display for DtdError {
336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337        match self {
338            Self::SlotOutOfRange { slot, slots } => {
339                write!(f, "DTD slot {slot} is out of range ({} slots)", slots)
340            }
341            Self::InvalidField { field, value } => {
342                write!(f, "DTD field {field:?} has invalid value {value}")
343            }
344            Self::FieldOutOfRange { field, value, max } => {
345                write!(f, "DTD field {field:?} value {value} exceeds {max}")
346            }
347            Self::NoAvailableSlot {
348                requested,
349                available,
350            } => write!(
351                f,
352                "requested {requested} timings but only {available} DTD slots are available"
353            ),
354            Self::ArithmeticOverflow => f.write_str("DTD timing arithmetic overflowed"),
355        }
356    }
357}
358
359impl std::error::Error for DtdError {}
360
361/// Errors returned by the strict resolution-to-EDID serializer.
362#[derive(Clone, Debug, PartialEq, Eq)]
363#[non_exhaustive]
364pub enum SerializeError {
365    /// Existing input is not an integral sequence of EDID blocks.
366    InvalidExistingLength {
367        /// Actual input length in bytes.
368        actual: usize,
369    },
370    /// An existing block failed strict validation.
371    InvalidExistingBlock {
372        /// Zero-based block index.
373        index: usize,
374        /// Validation failure from that block.
375        source: EdidError,
376    },
377    /// The base block's extension count disagrees with the supplied blocks.
378    ExtensionCountMismatch {
379        /// Count declared by the base block.
380        declared: usize,
381        /// Number of extension blocks supplied.
382        actual: usize,
383    },
384    /// A requested resolution could not produce a timing.
385    TimingUnavailable {
386        /// Zero-based resolution index.
387        index: usize,
388    },
389    /// A computed timing exceeds DTD field limits.
390    TimingDoesNotFit {
391        /// Zero-based resolution index.
392        index: usize,
393    },
394    /// No reusable DTD slot remains for a requested timing.
395    NoDtdSlot {
396        /// Zero-based resolution index that could not be written.
397        index: usize,
398    },
399    /// A manually supplied timing failed DTD validation.
400    InvalidTiming {
401        /// Zero-based timing index.
402        index: usize,
403        /// DTD validation failure.
404        source: DtdError,
405    },
406    /// The extension count cannot be represented by the base block byte.
407    TooManyExtensions {
408        /// Number of extension blocks supplied.
409        count: usize,
410    },
411}
412
413impl fmt::Display for SerializeError {
414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415        match self {
416            Self::InvalidExistingLength { actual } => {
417                write!(
418                    f,
419                    "existing EDID length {actual} is not a whole block sequence"
420                )
421            }
422            Self::InvalidExistingBlock { index, source } => {
423                write!(f, "existing EDID block {index} is invalid: {source}")
424            }
425            Self::ExtensionCountMismatch { declared, actual } => write!(
426                f,
427                "EDID declares {declared} extension blocks but supplied {actual}"
428            ),
429            Self::TooManyExtensions { count } => {
430                write!(f, "EDID contains too many extension blocks: {count}")
431            }
432            Self::TimingUnavailable { index } => {
433                write!(f, "resolution {index} could not produce a timing")
434            }
435            Self::TimingDoesNotFit { index } => {
436                write!(f, "resolution {index} does not fit an EDID DTD")
437            }
438            Self::NoDtdSlot { index } => {
439                write!(f, "no DTD slot is available for resolution {index}")
440            }
441            Self::InvalidTiming { index, source } => {
442                write!(f, "timing {index} is invalid: {source}")
443            }
444        }
445    }
446}
447impl std::error::Error for SerializeError {
448    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
449        match self {
450            Self::InvalidExistingBlock { source, .. } => Some(source),
451            Self::InvalidTiming { source, .. } => Some(source),
452            _ => None,
453        }
454    }
455}
456
457impl fmt::Display for EdidError {
458    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
459        match self {
460            Self::InvalidLength { expected, actual } => {
461                write!(
462                    f,
463                    "invalid EDID block length: expected {expected}, got {actual}"
464                )
465            }
466            Self::InvalidBlockSequenceLength { actual } => {
467                write!(f, "invalid EDID block sequence length: got {actual} bytes")
468            }
469            Self::InvalidHeader => f.write_str("invalid EDID base-block header"),
470            Self::InvalidChecksum { sum } => {
471                write!(f, "invalid EDID checksum: byte sum modulo 256 is {sum}")
472            }
473            Self::ExtensionCountMismatch { declared, actual } => write!(
474                f,
475                "EDID declares {declared} extension blocks but supplied {actual}"
476            ),
477            Self::ExtensionIndexOutOfRange { index, count } => write!(
478                f,
479                "extension index {index} is outside the {count}-extension list"
480            ),
481            Self::TooManyExtensions { count } => {
482                write!(f, "EDID contains too many extension blocks: {count}")
483            }
484            Self::UnsupportedVersion { major, minor } => {
485                write!(f, "unsupported EDID version {major}.{minor}")
486            }
487        }
488    }
489}
490
491impl std::error::Error for EdidError {}
492
493/// Errors returned while parsing an X11 / xrandr Modeline string.
494#[derive(Clone, Debug, PartialEq, Eq)]
495#[non_exhaustive]
496pub enum ModelineError {
497    /// Modeline string is empty or contains insufficient tokens.
498    InsufficientTokens,
499    /// A numeric parameter failed to parse.
500    InvalidNumber {
501        /// The invalid token.
502        token: String,
503    },
504    /// Invalid geometry (e.g. sync start < active, sync end < sync start, total < sync end).
505    InvalidGeometry(&'static str),
506    /// Pixel clock is zero or mathematically invalid.
507    InvalidPixelClock,
508}
509
510impl fmt::Display for ModelineError {
511    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512        match self {
513            Self::InsufficientTokens => f.write_str("Modeline string has insufficient tokens"),
514            Self::InvalidNumber { token } => {
515                write!(f, "invalid numeric token in Modeline: {token:?}")
516            }
517            Self::InvalidGeometry(reason) => write!(f, "invalid Modeline geometry: {reason}"),
518            Self::InvalidPixelClock => {
519                f.write_str("Modeline pixel clock must be positive and non-zero")
520            }
521        }
522    }
523}
524
525impl std::error::Error for ModelineError {}
526
527/// Errors returned while parsing hexadecimal EDID strings.
528#[derive(Clone, Debug, PartialEq, Eq)]
529#[non_exhaustive]
530pub enum HexError {
531    /// String contains a non-hexadecimal character.
532    InvalidHexCharacter {
533        /// Character byte offset.
534        offset: usize,
535        /// Invalid character.
536        character: char,
537    },
538    /// Hex string has an odd number of hexadecimal digits.
539    OddLength {
540        /// Total number of hex digits found.
541        length: usize,
542    },
543    /// Decoded byte count is not a multiple of EDID_BLOCK_SIZE (128 bytes).
544    InvalidLength {
545        /// Number of decoded bytes.
546        bytes: usize,
547    },
548    /// EDID block or sequence validation failed.
549    EdidError(EdidError),
550}
551
552impl fmt::Display for HexError {
553    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
554        match self {
555            Self::InvalidHexCharacter { offset, character } => {
556                write!(f, "invalid hex character {character:?} at index {offset}")
557            }
558            Self::OddLength { length } => {
559                write!(f, "hex string has odd length ({length} nibbles)")
560            }
561            Self::InvalidLength { bytes } => {
562                write!(
563                    f,
564                    "decoded {bytes} bytes, expected a multiple of 128 (EDID block size)"
565                )
566            }
567            Self::EdidError(err) => write!(f, "EDID validation error: {err}"),
568        }
569    }
570}
571
572impl std::error::Error for HexError {
573    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
574        match self {
575            Self::EdidError(err) => Some(err),
576            _ => None,
577        }
578    }
579}