tpt_protocol_core/
error.rs1use alloc::string::String;
2use core::fmt;
3
4#[derive(Clone, Debug, PartialEq)]
5#[non_exhaustive]
6pub enum Error {
7 Parse(String),
8 State(String),
9 Normalize(String),
10 Cbor(String),
11 Transport(String),
12 Config(String),
13 Checksum {
16 expected: u32,
17 actual: u32,
18 message: String,
19 },
20 Overflow {
21 max: usize,
22 actual: usize,
23 message: String,
24 },
25 InvalidFrame {
26 reason: String,
27 offset: usize,
28 },
29}
30
31impl Error {
32 pub fn parse(msg: impl Into<String>) -> Self {
33 Self::Parse(msg.into())
34 }
35
36 pub fn state(msg: impl Into<String>) -> Self {
37 Self::State(msg.into())
38 }
39
40 pub fn normalize(msg: impl Into<String>) -> Self {
41 Self::Normalize(msg.into())
42 }
43
44 pub fn cbor(msg: impl Into<String>) -> Self {
45 Self::Cbor(msg.into())
46 }
47
48 pub fn transport(msg: impl Into<String>) -> Self {
49 Self::Transport(msg.into())
50 }
51
52 pub fn config(msg: impl Into<String>) -> Self {
53 Self::Config(msg.into())
54 }
55
56 pub fn checksum(expected: u32, actual: u32, msg: impl Into<String>) -> Self {
57 Self::Checksum {
58 expected,
59 actual,
60 message: msg.into(),
61 }
62 }
63
64 pub fn overflow(max: usize, actual: usize, msg: impl Into<String>) -> Self {
65 Self::Overflow {
66 max,
67 actual,
68 message: msg.into(),
69 }
70 }
71
72 pub fn invalid_frame(reason: impl Into<String>, offset: usize) -> Self {
73 Self::InvalidFrame {
74 reason: reason.into(),
75 offset,
76 }
77 }
78}
79
80impl fmt::Display for Error {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 match self {
83 Self::Parse(msg) => write!(f, "parse error: {msg}"),
84 Self::State(msg) => write!(f, "state error: {msg}"),
85 Self::Normalize(msg) => write!(f, "normalize error: {msg}"),
86 Self::Cbor(msg) => write!(f, "cbor error: {msg}"),
87 Self::Transport(msg) => write!(f, "transport error: {msg}"),
88 Self::Config(msg) => write!(f, "config error: {msg}"),
89 Self::Checksum {
90 expected,
91 actual,
92 message,
93 } => {
94 write!(
95 f,
96 "checksum mismatch: expected {expected:#x}, got {actual:#x} — {message}"
97 )
98 }
99 Self::Overflow {
100 max,
101 actual,
102 message,
103 } => {
104 write!(f, "overflow: max {max} bytes, got {actual} — {message}")
105 }
106 Self::InvalidFrame { reason, offset } => {
107 write!(f, "invalid frame at offset {offset}: {reason}")
108 }
109 }
110 }
111}
112
113impl From<core::str::Utf8Error> for Error {
114 fn from(e: core::str::Utf8Error) -> Self {
115 Self::Parse(alloc::format!("UTF-8 error: {e}"))
116 }
117}
118
119#[cfg(feature = "std")]
120impl core::error::Error for Error {}