qrusty_client/
priority.rs1use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(untagged)]
14pub enum Priority {
15 Numeric(u64),
16 Text(String),
17}
18
19impl Default for Priority {
20 fn default() -> Self {
21 Priority::Numeric(0)
22 }
23}
24
25impl From<u64> for Priority {
26 fn from(n: u64) -> Self {
27 Priority::Numeric(n)
28 }
29}
30
31impl From<&str> for Priority {
32 fn from(s: &str) -> Self {
33 Priority::Text(s.to_owned())
34 }
35}
36
37impl From<String> for Priority {
38 fn from(s: String) -> Self {
39 Priority::Text(s)
40 }
41}
42
43impl std::fmt::Display for Priority {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 match self {
46 Priority::Numeric(n) => write!(f, "{}", n),
47 Priority::Text(s) => write!(f, "{}", s),
48 }
49 }
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 #[test]
57 fn serialize_numeric() {
58 let p = Priority::Numeric(42);
59 assert_eq!(serde_json::to_value(&p).unwrap(), serde_json::json!(42));
60 }
61
62 #[test]
63 fn serialize_text() {
64 let p = Priority::Text("alpha".to_owned());
65 assert_eq!(
66 serde_json::to_value(&p).unwrap(),
67 serde_json::json!("alpha")
68 );
69 }
70
71 #[test]
72 fn deserialize_numeric() {
73 let p: Priority = serde_json::from_value(serde_json::json!(100)).unwrap();
74 assert_eq!(p, Priority::Numeric(100));
75 }
76
77 #[test]
78 fn deserialize_text() {
79 let p: Priority = serde_json::from_value(serde_json::json!("beta")).unwrap();
80 assert_eq!(p, Priority::Text("beta".to_owned()));
81 }
82
83 #[test]
84 fn default_is_numeric_zero() {
85 assert_eq!(Priority::default(), Priority::Numeric(0));
86 }
87
88 #[test]
89 fn from_u64() {
90 let p: Priority = 99u64.into();
91 assert_eq!(p, Priority::Numeric(99));
92 }
93
94 #[test]
95 fn from_str() {
96 let p: Priority = "gamma".into();
97 assert_eq!(p, Priority::Text("gamma".to_owned()));
98 }
99
100 #[test]
101 fn from_string() {
102 let p: Priority = String::from("delta").into();
103 assert_eq!(p, Priority::Text("delta".to_owned()));
104 }
105
106 #[test]
107 fn display_numeric() {
108 assert_eq!(Priority::Numeric(7).to_string(), "7");
109 }
110
111 #[test]
112 fn display_text() {
113 assert_eq!(Priority::Text("foo".to_owned()).to_string(), "foo");
114 }
115
116 #[test]
117 fn round_trip_in_json_object() {
118 let body = serde_json::json!({
119 "queue": "test",
120 "priority": Priority::Numeric(50),
121 "payload": "hello"
122 });
123 assert_eq!(body["priority"], 50);
124
125 let body = serde_json::json!({
126 "queue": "test",
127 "priority": Priority::Text("abc".to_owned()),
128 "payload": "hello"
129 });
130 assert_eq!(body["priority"], "abc");
131 }
132}