msft_typelib/error.rs
1//! Error types for MSFT type library parsing.
2//!
3//! All errors are non-fatal data-validation failures. Because the parser
4//! is zero-copy and does not allocate, I/O errors are the caller's
5//! responsibility (load the file, then pass `&[u8]` to
6//! [`TypeLib::parse`](crate::TypeLib::parse)).
7
8use std::fmt;
9
10/// Errors that can occur when parsing an MSFT type library.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum Error {
13 /// The input buffer is too short for the expected structure.
14 TooShort {
15 /// Minimum number of bytes required.
16 expected: usize,
17 /// Actual number of bytes available.
18 actual: usize,
19 /// Human-readable name of the structure being parsed.
20 context: &'static str,
21 },
22 /// The file does not start with the expected `"MSFT"` magic bytes.
23 BadMagic {
24 /// Expected magic value (`0x5446534D`).
25 expected: u32,
26 /// Actual value found at offset 0.
27 got: u32,
28 },
29 /// A TypeInfo index is outside the valid range `0..typeinfo_count`.
30 TypeInfoOutOfRange {
31 /// The requested index.
32 index: usize,
33 /// Total number of TypeInfo entries in this library.
34 count: usize,
35 },
36 /// A required field or offset could not be read from the binary data.
37 ///
38 /// This typically indicates a truncated or corrupt type library.
39 InvalidData {
40 /// Human-readable description of what went wrong.
41 context: &'static str,
42 },
43}
44
45impl fmt::Display for Error {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 match self {
48 Error::TooShort {
49 expected,
50 actual,
51 context,
52 } => write!(
53 f,
54 "{context}: expected at least {expected} bytes, got {actual}"
55 ),
56 Error::BadMagic { expected, got } => {
57 write!(f, "bad magic: expected 0x{expected:08X}, got 0x{got:08X}")
58 }
59 Error::TypeInfoOutOfRange { index, count } => {
60 write!(f, "typeinfo index {index} out of range (count: {count})")
61 }
62 Error::InvalidData { context } => {
63 write!(f, "invalid data: {context}")
64 }
65 }
66 }
67}
68
69impl std::error::Error for Error {}