Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Priority de/serialization #11

Merged
merged 3 commits into from
Jan 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub enum Error {
#[cfg(feature = "async")]
InvalidHeaderValue(InvalidHeaderValue),
EmptyResponse,
UnknownPriority,
}

impl std::error::Error for Error {}
Expand All @@ -39,7 +40,8 @@ impl fmt::Display for Error {
Self::Url(e) => write!(f, "{}", e),
#[cfg(feature = "async")]
Self::InvalidHeaderValue(e) => write!(f, "{}", e),
Self::EmptyResponse => write!(f, "Empty Response"),
Self::EmptyResponse => write!(f, "Empty response"),
Self::UnknownPriority => write!(f, "Unknown priority"),
}
}
}
Expand Down
137 changes: 126 additions & 11 deletions src/payload/priority.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
// Copyright (c) 2022 Yuki Kishimoto
// Distributed under the MIT software license

use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::str::FromStr;

use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

use crate::error::Error;

#[repr(u8)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
Expand All @@ -15,13 +19,72 @@ pub enum Priority {
Min = 1,
}

impl fmt::Display for Priority {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}

impl Priority {
pub fn from_u8(priority: u8) -> Result<Self, Error> {
match priority {
5 => Ok(Priority::Max),
4 => Ok(Priority::High),
3 => Ok(Priority::Default),
2 => Ok(Priority::Low),
1 => Ok(Priority::Min),
_ => Err(Error::UnknownPriority),
}
}

/// Convert to `u8`
#[inline]
pub fn as_u8(&self) -> u8 {
*self as u8
}

/// Convert to `&str`
pub fn as_str(&self) -> &str {
match self {
Self::Max => "max",
Self::High => "high",
Self::Default => "default",
Self::Low => "low",
Self::Min => "min",
}
}
}

impl FromStr for Priority {
type Err = Error;

fn from_str(priority: &str) -> Result<Self, Self::Err> {
match priority {
"max" | "urgent" => Ok(Self::Max),
"high" => Ok(Self::High),
"default" => Ok(Self::Default),
"low" => Ok(Self::Low),
"min" => Ok(Self::Min),
_ => Err(Error::UnknownPriority),
}
}
}

#[derive(Deserialize)]
#[serde(untagged)]
enum NumberOrString {
Number(u8),
String(String),
}

impl Serialize for Priority {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let p: u8 = *self as u8;
p.serialize(serializer)
// According to ntfy docs, the priority in the JSON payload must be a number.
// https://docs.ntfy.sh/subscribe/api/#json-message-format
serializer.serialize_u8(self.as_u8())
}
}

Expand All @@ -30,13 +93,65 @@ impl<'de> Deserialize<'de> for Priority {
where
D: Deserializer<'de>,
{
match u8::deserialize(deserializer)? {
5 => Ok(Priority::Max),
4 => Ok(Priority::High),
3 => Ok(Priority::Default),
2 => Ok(Priority::Low),
1 => Ok(Priority::Min),
o => Err(Error::custom(format_args!("Invalid value: {}", o))),
match NumberOrString::deserialize(deserializer)? {
NumberOrString::Number(priority) => {
Priority::from_u8(priority).map_err(de::Error::custom)
}
NumberOrString::String(priority) => {
Self::from_str(&priority).map_err(de::Error::custom)
}
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_deserialize() {
let json = serde_json::json!(5);
let priority: Priority = serde_json::from_value(json).unwrap();
assert_eq!(priority, Priority::Max);

let json = serde_json::json!(4);
let priority: Priority = serde_json::from_value(json).unwrap();
assert_eq!(priority, Priority::High);

let json = serde_json::json!(3);
let priority: Priority = serde_json::from_value(json).unwrap();
assert_eq!(priority, Priority::Default);

let json = serde_json::json!(2);
let priority: Priority = serde_json::from_value(json).unwrap();
assert_eq!(priority, Priority::Low);

let json = serde_json::json!(1);
let priority: Priority = serde_json::from_value(json).unwrap();
assert_eq!(priority, Priority::Min);

let json = serde_json::json!("urgent");
let priority: Priority = serde_json::from_value(json).unwrap();
assert_eq!(priority, Priority::Max);

let json = serde_json::json!("max");
let priority: Priority = serde_json::from_value(json).unwrap();
assert_eq!(priority, Priority::Max);

let json = serde_json::json!("high");
let priority: Priority = serde_json::from_value(json).unwrap();
assert_eq!(priority, Priority::High);

let json = serde_json::json!("default");
let priority: Priority = serde_json::from_value(json).unwrap();
assert_eq!(priority, Priority::Default);

let json = serde_json::json!("low");
let priority: Priority = serde_json::from_value(json).unwrap();
assert_eq!(priority, Priority::Low);

let json = serde_json::json!("min");
let priority: Priority = serde_json::from_value(json).unwrap();
assert_eq!(priority, Priority::Min);
}
}
Loading