1use serde::{Deserialize, Serialize};
4use serde_json::value::RawValue;
5
6use crate::Error;
7use crate::error::PayloadError;
8
9pub fn json<T: Serialize + ?Sized>(value: &T) -> Result<Box<RawValue>, Error> {
32 serde_json::value::to_raw_value(value).map_err(|e| Error::Payload(PayloadError::encode(e)))
33}
34
35pub trait PayloadExt: sealed::Sealed {
52 fn decode<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error>;
58}
59
60impl PayloadExt for RawValue {
61 fn decode<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
62 serde_json::from_str(self.get()).map_err(|e| Error::Payload(PayloadError::decode(e)))
63 }
64}
65
66impl PayloadExt for Box<RawValue> {
67 fn decode<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
68 (**self).decode()
69 }
70}
71
72impl PayloadExt for Option<Box<RawValue>> {
73 fn decode<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
74 self.as_deref()
75 .ok_or_else(|| Error::Payload(PayloadError::missing()))?
76 .decode()
77 }
78}
79
80mod sealed {
81 use serde_json::value::RawValue;
82
83 pub trait Sealed {}
84 impl Sealed for RawValue {}
85 impl Sealed for Box<RawValue> {}
86 impl Sealed for Option<Box<RawValue>> {}
87}
88
89#[cfg(test)]
90mod tests {
91 #![allow(clippy::unwrap_used)]
92 use super::*;
93
94 #[derive(Debug, PartialEq, Serialize, Deserialize)]
95 struct Message {
96 text: String,
97 }
98
99 #[test]
100 fn round_trip() {
101 let raw = json(&Message { text: "hi".into() }).unwrap();
102 assert_eq!(raw.get(), r#"{"text":"hi"}"#);
103 assert_eq!(
104 raw.decode::<Message>().unwrap(),
105 Message { text: "hi".into() }
106 );
107 assert_eq!(
108 Some(raw).decode::<Message>().unwrap(),
109 Message { text: "hi".into() }
110 );
111 let raw = json("x").unwrap();
113 assert_eq!(raw.decode::<&str>().unwrap(), "x");
114 }
115
116 #[test]
117 fn errors() {
118 let mut keys = std::collections::HashMap::new();
119 keys.insert((1, 2), 3);
120 let e = json(&keys).unwrap_err();
121 assert!(matches!(e, Error::Payload(_)), "{e}");
122 assert!(e.to_string().starts_with("encoding the payload: "), "{e}");
123 assert!(!e.is_retryable());
124
125 let e = json("x").unwrap().decode::<Message>().unwrap_err();
126 assert!(e.to_string().starts_with("decoding the payload: "), "{e}");
127 assert!(std::error::Error::source(&e).is_some());
128 let e = None::<Box<RawValue>>.decode::<Message>().unwrap_err();
129 assert_eq!(e.to_string(), "decoding the payload: no payload");
130 }
131}