sapio_base/
serialization_helpers.rs

1// Copyright Judica, Inc 2021
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4//  License, v. 2.0. If a copy of the MPL was not distributed with this
5//  file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
7//! Helpers for serializing Arcs
8use schemars::JsonSchema;
9use serde::{Deserialize, Deserializer, Serialize, Serializer};
10use std::borrow::Borrow;
11use std::sync::Arc;
12
13/// Serializable Arc Type
14#[derive(
15    Serialize, Deserialize, JsonSchema, Clone, Debug, PartialEq, PartialOrd, Eq, Hash, Ord,
16)]
17#[serde(bound = "T: Serialize + for<'d> Deserialize<'d> + JsonSchema + std::fmt::Debug + Clone ")]
18#[serde(transparent)]
19pub struct SArc<T>(
20    #[serde(serialize_with = "serializer")]
21    #[serde(deserialize_with = "deserializer")]
22    pub Arc<T>,
23);
24/// arc serializer
25pub fn serializer<T, S>(v: &Arc<T>, s: S) -> Result<S::Ok, S::Error>
26where
27    S: Serializer,
28    T: Serialize,
29{
30    let b: &T = v.borrow();
31    b.serialize(s)
32}
33/// arc deserializer
34pub fn deserializer<'de, T, D>(d: D) -> Result<Arc<T>, D::Error>
35where
36    D: Deserializer<'de>,
37    T: Deserialize<'de>,
38{
39    Ok(Arc::new(T::deserialize(d)?))
40}
41
42#[cfg(test)]
43mod test {
44    use super::*;
45    #[test]
46    fn test_sarc_ser() -> Result<(), Box<dyn std::error::Error>> {
47        assert_eq!(serde_json::to_string(&SArc(Arc::new(1)))?, "1");
48        Ok(())
49    }
50}