1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
use serde::de::{self, Deserialize, DeserializeOwned, Deserializer};
use serde::ser::{self, Serialize, Serializer};
/// Utility wrapper to force values through JSON serialization.
///
/// By default `procspawn` will use [`bincode`](https://github.com/servo/bincode) to serialize
/// data across process boundaries. This has some limitations which can cause serialization
/// or deserialization to fail for some types.
///
/// Since JSON is generally better supported in the serde ecosystem this lets you work
/// around some known bugs.
///
/// * serde flatten not being supported: [bincode#245](https://github.com/servo/bincode/issues/245)
/// * vectors with unknown length not supported: [bincode#167](https://github.com/servo/bincode/issues/167)
///
/// Examples:
///
/// ```rust,no_run
/// use procspawn::{spawn, serde::Json};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize, Debug)]
/// struct InnerStruct {
/// value: u64,
/// }
///
/// #[derive(Serialize, Deserialize, Debug)]
/// struct BadStruct {
/// #[serde(flatten)]
/// inner: InnerStruct,
/// }
///
/// let handle = spawn((), |()| {
/// Json(BadStruct {
/// inner: InnerStruct { value: 42 },
/// })
/// });
/// let value = handle.join().unwrap().0;
/// ```
///
/// This requires the `json` feature.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Json<T>(pub T);
impl<T: Serialize> Serialize for Json<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let json = serde_json::to_string(&self.0).map_err(|e| ser::Error::custom(e.to_string()))?;
serializer.serialize_str(&json)
}
}
impl<'de, T: DeserializeOwned> Deserialize<'de> for Json<T> {
fn deserialize<D>(deserializer: D) -> Result<Json<T>, D::Error>
where
D: Deserializer<'de>,
{
let json =
String::deserialize(deserializer).map_err(|e| de::Error::custom(e.to_string()))?;
Ok(Json(
serde_json::from_str(&json).map_err(|e| de::Error::custom(e.to_string()))?,
))
}
}