use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use crate::Error;
use crate::error::PayloadError;
pub fn json<T: Serialize + ?Sized>(value: &T) -> Result<Box<RawValue>, Error> {
serde_json::value::to_raw_value(value).map_err(|e| Error::Payload(PayloadError::encode(e)))
}
pub trait PayloadExt: sealed::Sealed {
fn decode<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error>;
}
impl PayloadExt for RawValue {
fn decode<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
serde_json::from_str(self.get()).map_err(|e| Error::Payload(PayloadError::decode(e)))
}
}
impl PayloadExt for Box<RawValue> {
fn decode<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
(**self).decode()
}
}
impl PayloadExt for Option<Box<RawValue>> {
fn decode<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
self.as_deref()
.ok_or_else(|| Error::Payload(PayloadError::missing()))?
.decode()
}
}
mod sealed {
use serde_json::value::RawValue;
pub trait Sealed {}
impl Sealed for RawValue {}
impl Sealed for Box<RawValue> {}
impl Sealed for Option<Box<RawValue>> {}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Message {
text: String,
}
#[test]
fn round_trip() {
let raw = json(&Message { text: "hi".into() }).unwrap();
assert_eq!(raw.get(), r#"{"text":"hi"}"#);
assert_eq!(
raw.decode::<Message>().unwrap(),
Message { text: "hi".into() }
);
assert_eq!(
Some(raw).decode::<Message>().unwrap(),
Message { text: "hi".into() }
);
let raw = json("x").unwrap();
assert_eq!(raw.decode::<&str>().unwrap(), "x");
}
#[test]
fn errors() {
let mut keys = std::collections::HashMap::new();
keys.insert((1, 2), 3);
let e = json(&keys).unwrap_err();
assert!(matches!(e, Error::Payload(_)), "{e}");
assert!(e.to_string().starts_with("encoding the payload: "), "{e}");
assert!(!e.is_retryable());
let e = json("x").unwrap().decode::<Message>().unwrap_err();
assert!(e.to_string().starts_with("decoding the payload: "), "{e}");
assert!(std::error::Error::source(&e).is_some());
let e = None::<Box<RawValue>>.decode::<Message>().unwrap_err();
assert_eq!(e.to_string(), "decoding the payload: no payload");
}
}