1use std::{error::Error, fmt::Display};
15
16use crate::{PayloadEncoding, UCode, UStatus};
17
18pub mod codec;
20pub mod loan;
22pub mod stable;
23
24#[derive(Clone, Debug, Eq, PartialEq)]
26#[non_exhaustive]
27pub enum UWireError {
28 BufferTooSmall {
30 expected: usize,
32 actual: usize,
34 },
35 InvalidPayload(String),
37 MissingEncoding,
39 MissingPayload,
41 UnsupportedEncoding {
43 expected: Box<PayloadEncoding>,
45 actual: Box<PayloadEncoding>,
47 },
48 SerializationError(String),
50}
51
52impl UWireError {
53 #[must_use]
55 pub fn buffer_too_small(expected: usize, actual: usize) -> Self {
56 Self::BufferTooSmall { expected, actual }
57 }
58
59 #[must_use]
61 pub fn invalid_payload(message: impl Into<String>) -> Self {
62 Self::InvalidPayload(message.into())
63 }
64
65 #[must_use]
67 pub fn invalid_payload_length(expected: usize, actual: usize) -> Self {
68 Self::invalid_payload(format!("payload length must be {expected}, got {actual}"))
69 }
70
71 #[must_use]
73 pub fn serialization_error(message: impl Into<String>) -> Self {
74 Self::SerializationError(message.into())
75 }
76}
77
78impl Display for UWireError {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 match self {
81 Self::BufferTooSmall { expected, actual } => f.write_fmt(format_args!(
82 "buffer too small: expected at least {expected} bytes, got {actual} bytes"
83 )),
84 Self::InvalidPayload(message) => {
85 f.write_fmt(format_args!("invalid payload: {message}"))
86 }
87 Self::MissingEncoding => f.write_str("frame payload has no encoding metadata"),
88 Self::MissingPayload => f.write_str("frame has no payload"),
89 Self::UnsupportedEncoding { expected, actual } => f.write_fmt(format_args!(
90 "unsupported payload encoding: expected {expected:?}; got {actual:?}",
91 )),
92 Self::SerializationError(message) => {
93 f.write_fmt(format_args!("serialization error: {message}"))
94 }
95 }
96 }
97}
98
99impl Error for UWireError {}
100
101impl From<UWireError> for UStatus {
102 fn from(value: UWireError) -> Self {
103 UStatus::fail_with_code(UCode::InvalidArgument, value.to_string())
104 }
105}