Skip to main content

onnx_rs/
error.rs

1use core::fmt;
2
3/// Errors that can occur when parsing ONNX protobuf bytes.
4///
5/// # Examples
6///
7/// ```
8/// use onnx_rs::{parse, Error};
9///
10/// // Empty input is a valid (default) model in protobuf
11/// let model = parse(&[]).unwrap();
12/// assert_eq!(model.ir_version, 0);
13///
14/// // A truncated varint produces an error
15/// let err = parse(&[0x08]).unwrap_err();
16/// assert!(err.to_string().contains("unexpected EOF"));
17/// ```
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum Error {
20    UnexpectedEof {
21        offset: usize,
22        context: &'static str,
23    },
24    InvalidVarint {
25        offset: usize,
26    },
27    InvalidWireType {
28        value: u8,
29        offset: usize,
30    },
31    InvalidEnumValue {
32        enum_name: &'static str,
33        value: i32,
34    },
35    InvalidUtf8 {
36        offset: usize,
37    },
38    TruncatedMessage {
39        offset: usize,
40        expected: usize,
41        available: usize,
42    },
43}
44
45impl fmt::Display for Error {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        match self {
48            Error::UnexpectedEof { offset, context } => {
49                write!(f, "unexpected EOF at offset {offset} while {context}")
50            }
51            Error::InvalidVarint { offset } => {
52                write!(f, "invalid varint encoding at offset {offset}")
53            }
54            Error::InvalidWireType { value, offset } => {
55                write!(f, "invalid wire type {value} at offset {offset}")
56            }
57            Error::InvalidEnumValue { enum_name, value } => {
58                write!(f, "invalid {enum_name} enum value: {value}")
59            }
60            Error::InvalidUtf8 { offset } => {
61                write!(f, "invalid UTF-8 string at offset {offset}")
62            }
63            Error::TruncatedMessage {
64                offset,
65                expected,
66                available,
67            } => {
68                write!(
69                    f,
70                    "truncated message at offset {offset}: expected {expected} bytes but only {available} available"
71                )
72            }
73        }
74    }
75}
76
77impl std::error::Error for Error {}