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
29impl From<postcard::Error> for ProtocolError {
30 fn from(e: postcard::Error) -> Self {
31 ProtocolError::Serialization(e.to_string())
32 }
33}
34
35pub type Result<T> = std::result::Result<T, ProtocolError>;
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41
42 #[test]
43 fn test_error_display() {
44 let err = ProtocolError::Serialization("test".to_string());
45 assert_eq!(err.to_string(), "Serialization error: test");
46
47 let err = ProtocolError::Deserialization("bad data".to_string());
48 assert_eq!(err.to_string(), "Deserialization error: bad data");
49
50 let err = ProtocolError::MessageTooLarge(1000, 500);
51 assert_eq!(err.to_string(), "Message size 1000 exceeds maximum 500");
52
53 let err = ProtocolError::InvalidFormat("missing field".to_string());
54 assert_eq!(err.to_string(), "Invalid message format: missing field");
55
56 let err = ProtocolError::VersionMismatch {
57 expected: 1,
58 actual: 2,
59 };
60 assert_eq!(
61 err.to_string(),
62 "Protocol version mismatch: expected 1, got 2"
63 );
64 }
65
66 #[test]
67 fn test_error_debug() {
68 let err = ProtocolError::Serialization("test".to_string());
69 let debug = format!("{:?}", err);
70 assert!(debug.contains("Serialization"));
71 }
72
73 #[test]
74 fn test_result_type() {
75 fn returns_ok() -> Result<i32> {
76 Ok(42)
77 }
78 let ok = returns_ok();
79 assert!(ok.is_ok());
80 assert_eq!(ok.unwrap(), 42);
81
82 fn returns_err() -> Result<i32> {
83 Err(ProtocolError::InvalidFormat("test".to_string()))
84 }
85 let err = returns_err();
86 assert!(err.is_err());
87 }
88}