use core::fmt; use std::{error::Error, fmt::Display}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] pub struct ChatMessage { pub author: String, pub message: String, } impl Display for ChatMessage { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Message from {}: {}", self.author, self.message) } } impl TryFrom> for ChatMessage { type Error = NatsParsingError; fn try_from(value: Vec) -> Result { let as_string = &String::from_utf8(value).map_err(|_| NatsParsingError::NoValidUtf8)?; let to_return = serde_json::from_str(as_string).map_err(|_| NatsParsingError::CannotDeserializeJson)?; Ok(to_return) } } impl From for Vec { fn from(value: ChatMessage) -> Self { let json_string_utf8 = serde_json::to_string(&value).expect("Cannot serialize message"); json_string_utf8.into_bytes() } } #[derive(Debug)] pub enum NatsParsingError { // Message was no string at all NoValidUtf8, // Message could be invalid json or json not matching the struct you want to deserialize CannotDeserializeJson, } impl Error for NatsParsingError {} impl Display for NatsParsingError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let message = match self { NatsParsingError::NoValidUtf8 => "NATS message was no valid UTF-8 string.", NatsParsingError::CannotDeserializeJson => { "NATS message is not a json of expected structure." } }; writeln!(f, "{}", message) } }