Clean up code

This commit is contained in:
2023-05-07 17:11:17 +02:00
parent 0c0fc8e227
commit b91b022cbb
3 changed files with 131 additions and 53 deletions

View File

@ -0,0 +1,49 @@
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<Vec<u8>> for ChatMessage {
type Error = NatsParsingError;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
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)
}
}
#[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 valid / expected json."
}
};
writeln!(f, "{}", message)
}
}