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.
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19 */
20
21pub mod serialization {
22    pub use serde::{Deserialize, Deserializer, Serialize, Serializer};
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    /// pub use crate::rumtk_core::json::serialization::{Serialize};
37    /// use crate::rumtk_core::strings::RUMString;
38    /// use crate::rumtk_core::rumtk_serialize;
39    ///
40    /// #[derive(Serialize)]
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    /// pub use crate::rumtk_core::json::serialization::{Serialize};
55    /// use crate::rumtk_core::strings::RUMString;
56    /// use crate::rumtk_core::rumtk_serialize;
57    ///
58    /// #[derive(Serialize)]
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::json::serialization::{Deserialize, Serialize};
75            use $crate::strings::format_compact;
76            match to_string(&$object) {
77                Ok(s) => Ok(s),
78                Err(e) => Err(format_compact!(
79                    "Failed to serialize object because of {}",
80                    e
81                )),
82            }
83        }};
84        ( $object:expr, $pretty:expr ) => {{
85            use $crate::json::serialization::{to_string, to_string_pretty};
86            use $crate::json::serialization::{Deserialize, Serialize};
87            use $crate::strings::format_compact;
88            match $pretty {
89                true => match to_string_pretty(&$object) {
90                    Ok(s) => Ok(s),
91                    Err(e) => Err(format_compact!(
92                        "Failed to serialize object because of {}",
93                        e
94                    )),
95                },
96                false => match to_string(&$object) {
97                    Ok(s) => Ok(s),
98                    Err(e) => Err(format_compact!(
99                        "Failed to serialize object because of {}",
100                        e
101                    )),
102                },
103            }
104        }};
105    }
106
107    ///
108    /// Deserialization macro which will take a JSON string representation and return an instance
109    /// of the specified type.
110    ///
111    /// Pass the json string to deserialize. You will need to specify the expected type that will
112    /// be generated.
113    ///
114    /// # Example
115    ///
116    /// ```
117    /// pub use crate::rumtk_core::json::serialization::{Serialize, Deserialize};
118    /// use crate::rumtk_core::strings::RUMString;
119    /// use crate::rumtk_core::{rumtk_serialize, rumtk_deserialize};
120    ///
121    /// #[derive(Serialize, Deserialize, PartialEq)]
122    /// struct MyStruct {
123    ///     hello: RUMString
124    /// }
125    ///
126    /// let hw = MyStruct{hello: RUMString::from("World")};
127    /// let hw_str = rumtk_serialize!(&hw, true).unwrap();
128    /// let new_hw: MyStruct = rumtk_deserialize!(&hw_str).unwrap();
129    ///
130    /// assert!(
131    ///    new_hw == hw,
132    ///    "Deserialized JSON does not match the expected value!"
133    /// );
134    ///
135    /// ```
136    ///
137    #[macro_export]
138    macro_rules! rumtk_deserialize {
139        ( $string:expr ) => {{
140            use $crate::json::serialization::from_str;
141            use $crate::json::serialization::{Deserialize, Serialize};
142            from_str(&$string)
143        }};
144    }
145}