facet_msgpack/
error.rs

1//! Error types for MsgPack Tier-2 JIT parsing.
2
3use core::fmt;
4
5/// MsgPack parsing error.
6#[derive(Debug, Clone)]
7pub struct MsgPackError {
8    /// Error code from JIT
9    pub code: i32,
10    /// Position in input where error occurred
11    pub pos: usize,
12    /// Human-readable message
13    pub message: String,
14}
15
16impl fmt::Display for MsgPackError {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        write!(f, "{} at position {}", self.message, self.pos)
19    }
20}
21
22impl std::error::Error for MsgPackError {}
23
24impl miette::Diagnostic for MsgPackError {
25    fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
26        Some(Box::new(format!("msgpack::error::{}", self.code)))
27    }
28}
29
30/// MsgPack JIT error codes.
31pub mod codes {
32    /// Unexpected end of input
33    pub const UNEXPECTED_EOF: i32 = -100;
34    /// Invalid type tag for expected bool
35    pub const EXPECTED_BOOL: i32 = -101;
36    /// Invalid type tag for expected array
37    pub const EXPECTED_ARRAY: i32 = -102;
38    /// Invalid type tag for expected bin/bytes
39    pub const EXPECTED_BIN: i32 = -103;
40    /// Invalid type tag for expected integer
41    pub const EXPECTED_INT: i32 = -104;
42    /// Integer value doesn't fit in target type
43    pub const INT_OVERFLOW: i32 = -105;
44    /// Array/bin count doesn't fit in usize
45    pub const COUNT_OVERFLOW: i32 = -106;
46    /// Sequence underflow (decrement when remaining is 0)
47    pub const SEQ_UNDERFLOW: i32 = -107;
48    /// Unsupported operation (triggers fallback)
49    pub const UNSUPPORTED: i32 = -1;
50}
51
52impl MsgPackError {
53    /// Create an error from a JIT error code and position.
54    pub fn from_code(code: i32, pos: usize) -> Self {
55        let message = match code {
56            codes::UNEXPECTED_EOF => "unexpected end of input".to_string(),
57            codes::EXPECTED_BOOL => "expected bool (0xC2 or 0xC3)".to_string(),
58            codes::EXPECTED_ARRAY => "expected array tag (fixarray/array16/array32)".to_string(),
59            codes::EXPECTED_BIN => "expected bin tag (bin8/bin16/bin32)".to_string(),
60            codes::EXPECTED_INT => "expected integer tag".to_string(),
61            codes::INT_OVERFLOW => "integer value overflows target type".to_string(),
62            codes::COUNT_OVERFLOW => "count too large for platform".to_string(),
63            codes::SEQ_UNDERFLOW => "sequence underflow (internal error)".to_string(),
64            codes::UNSUPPORTED => "unsupported operation".to_string(),
65            _ => format!("unknown error code {}", code),
66        };
67        Self { code, pos, message }
68    }
69}