1use core::fmt;
4
5#[derive(Debug, Clone)]
7pub struct XdrError {
8 pub code: i32,
10 pub pos: usize,
12 pub message: String,
14}
15
16impl fmt::Display for XdrError {
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 XdrError {}
23
24pub mod codes {
26 pub const UNEXPECTED_EOF: i32 = -100;
28 pub const INVALID_BOOL: i32 = -101;
30 pub const INVALID_OPTIONAL: i32 = -102;
32 pub const INVALID_VARIANT: i32 = -103;
34 pub const INVALID_UTF8: i32 = -104;
36 pub const UNSUPPORTED_TYPE: i32 = -105;
38 pub const ALIGNMENT_ERROR: i32 = -106;
40}
41
42impl XdrError {
43 pub fn from_code(code: i32, pos: usize) -> Self {
45 let message = match code {
46 codes::UNEXPECTED_EOF => "unexpected end of input".to_string(),
47 codes::INVALID_BOOL => "invalid boolean value (must be 0 or 1)".to_string(),
48 codes::INVALID_OPTIONAL => "invalid optional discriminant (must be 0 or 1)".to_string(),
49 codes::INVALID_VARIANT => "invalid enum discriminant".to_string(),
50 codes::INVALID_UTF8 => "invalid UTF-8 in string".to_string(),
51 codes::UNSUPPORTED_TYPE => "unsupported type for XDR".to_string(),
52 codes::ALIGNMENT_ERROR => "position not aligned to 4 bytes".to_string(),
53 _ => format!("unknown error code {}", code),
54 };
55 Self { code, pos, message }
56 }
57
58 pub fn new(code: i32, pos: usize, message: impl Into<String>) -> Self {
60 Self {
61 code,
62 pos,
63 message: message.into(),
64 }
65 }
66}
67
68#[derive(Debug)]
70pub struct XdrSerializeError {
71 pub message: String,
73}
74
75impl fmt::Display for XdrSerializeError {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 f.write_str(&self.message)
78 }
79}
80
81impl std::error::Error for XdrSerializeError {}
82
83impl XdrSerializeError {
84 pub fn new(message: impl Into<String>) -> Self {
86 Self {
87 message: message.into(),
88 }
89 }
90}