Skip to main content

rumtk_core/
json.rs

1/*
2 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 * This toolkit aims to be reliable, simple, performant, and standards compliant.
4 * Copyright (C) 2025  Luis M. Santos, M.D. <lsantos@medicalmasses.com>
5 * Copyright (C) 2025  MedicalMasses L.L.C. <contact@medicalmasses.com>
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19 */
20
21pub mod serialization {
22    pub use crate::types::{RUMDeserialize, RUMDeserializer, RUMSerialize, RUMSerializer};
23    pub use serde_json::{from_str, to_string, to_string_pretty};
24
25    ///
26    /// Serialization macro which will take an object instance decorated with [Serialize] trait
27    /// from serde and return the JSON string representation.
28    ///
29    /// You can pass up to two parameters. The first parameter is the serializable object instance.
30    /// The second parameter is a boolean indicating whether to pretty print. Omit the second
31    /// parameter if not debugging to save on bytes transferred around.
32    ///
33    /// # Examples
34    /// ## Pretty Print
35    /// ```
36    /// use rumtk_core::json::serialization::{RUMSerialize};
37    /// use rumtk_core::strings::RUMString;
38    /// use rumtk_core::rumtk_serialize;
39    ///
40    /// #[derive(RUMSerialize)]
41    /// struct MyStruct {
42    ///     hello: RUMString
43    /// }
44    ///
45    /// let hw = MyStruct{hello: RUMString::from("World")};
46    /// let hw_str = rumtk_serialize!(&hw, true).unwrap();
47    ///
48    /// assert!(hw_str.len() > 0, "Empty JSON string generated from the test struct!");
49    ///
50    /// ```
51    ///
52    /// ## Default
53    /// ```
54    /// use rumtk_core::json::serialization::{RUMSerialize};
55    /// use rumtk_core::strings::RUMString;
56    /// use rumtk_core::rumtk_serialize;
57    ///
58    /// #[derive(RUMSerialize)]
59    /// struct MyStruct {
60    ///     hello: RUMString
61    /// }
62    ///
63    /// let hw = MyStruct{hello: RUMString::from("World")};
64    /// let hw_str = rumtk_serialize!(&hw).unwrap();
65    ///
66    /// assert!(hw_str.len() > 0, "Empty JSON string generated from the test struct!");
67    ///
68    /// ```
69    ///
70    #[macro_export]
71    macro_rules! rumtk_serialize {
72        ( $object:expr ) => {{
73            use $crate::json::serialization::{to_string, to_string_pretty};
74            use $crate::strings::rumtk_format;
75
76            match to_string(&$object) {
77                Ok(s) => Ok(s),
78                Err(e) => Err(rumtk_format!("Failed to serialize object because of {}", e)),
79            }
80        }};
81        ( $object:expr, $pretty:expr ) => {{
82            use $crate::json::serialization::{to_string, to_string_pretty};
83            use $crate::strings::rumtk_format;
84
85            match $pretty {
86                true => match to_string_pretty(&$object) {
87                    Ok(s) => Ok(s),
88                    Err(e) => Err(rumtk_format!("Failed to serialize object because of {}", e)),
89                },
90                false => match to_string(&$object) {
91                    Ok(s) => Ok(s),
92                    Err(e) => Err(rumtk_format!("Failed to serialize object because of {}", e)),
93                },
94            }
95        }};
96    }
97
98    ///
99    /// Deserialization macro which will take a JSON string representation and return an instance
100    /// of the specified type.
101    ///
102    /// Pass the json string to deserialize. You will need to specify the expected type that will
103    /// be generated.
104    ///
105    /// # Example
106    ///
107    /// ```
108    /// use rumtk_core::json::serialization::{RUMSerialize, RUMDeserialize};
109    /// use rumtk_core::strings::RUMString;
110    /// use rumtk_core::{rumtk_serialize, rumtk_deserialize};
111    ///
112    /// #[derive(RUMSerialize, RUMDeserialize, PartialEq)]
113    /// struct MyStruct {
114    ///     hello: RUMString
115    /// }
116    ///
117    /// let hw = MyStruct{hello: RUMString::from("World")};
118    /// let hw_str = rumtk_serialize!(&hw, true).unwrap();
119    /// let new_hw: MyStruct = rumtk_deserialize!(&hw_str).unwrap();
120    ///
121    /// assert!(
122    ///    new_hw == hw,
123    ///    "Deserialized JSON does not match the expected value!"
124    /// );
125    ///
126    /// ```
127    ///
128    #[macro_export]
129    macro_rules! rumtk_deserialize {
130        ( $string:expr ) => {{
131            use $crate::json::serialization::from_str;
132
133            from_str(&$string)
134        }};
135    }
136}