1use thiserror::Error;
4
5#[derive(Debug, Error)]
7pub enum ProtocolError {
8 #[error("Serialization error: {0}")]
10 Serialization(String),
11
12 #[error("Deserialization error: {0}")]
14 Deserialization(String),
15
16 #[error("Message size {0} exceeds maximum {1}")]
18 MessageTooLarge(usize, usize),
19
20 #[error("Invalid message format: {0}")]
22 InvalidFormat(String),
23
24 #[error("Protocol version mismatch: expected {expected}, got {actual}")]
26 VersionMismatch { expected: u32, actual: u32 },
27
28 #[error("Unsupported wire format: {0}")]
30 UnsupportedFormat(String),
31}
32
33impl From<postcard::Error> for ProtocolError {
34 fn from(e: postcard::Error) -> Self {
35 ProtocolError::Serialization(e.to_string())
36 }
37}
38
39pub type Result<T> = std::result::Result<T, ProtocolError>;
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 #[test]
47 fn test_error_display() {
48 let err = ProtocolError::Serialization("test".to_string());
49 assert_eq!(err.to_string(), "Serialization error: test");
50
51 let err = ProtocolError::Deserialization("bad data".to_string());
52 assert_eq!(err.to_string(), "Deserialization error: bad data");
53
54 let err = ProtocolError::MessageTooLarge(1000, 500);
55 assert_eq!(err.to_string(), "Message size 1000 exceeds maximum 500");
56
57 let err = ProtocolError::InvalidFormat("missing field".to_string());
58 assert_eq!(err.to_string(), "Invalid message format: missing field");
59
60 let err = ProtocolError::VersionMismatch {
61 expected: 1,
62 actual: 2,
63 };
64 assert_eq!(
65 err.to_string(),
66 "Protocol version mismatch: expected 1, got 2"
67 );
68 }
69
70 #[test]
71 fn test_error_debug() {
72 let err = ProtocolError::Serialization("test".to_string());
73 let debug = format!("{:?}", err);
74 assert!(debug.contains("Serialization"));
75 }
76
77 #[test]
78 fn test_result_type() {
79 fn returns_ok() -> Result<i32> {
80 Ok(42)
81 }
82 let ok = returns_ok();
83 assert!(ok.is_ok());
84 assert_eq!(ok.unwrap(), 42);
85
86 fn returns_err() -> Result<i32> {
87 Err(ProtocolError::InvalidFormat("test".to_string()))
88 }
89 let err = returns_err();
90 assert!(err.is_err());
91 }
92}