glue/
util.rs

1//! This module provides abstractions for serializing and deserializing data into various formats, specifically JSON strings and byte arrays.
2//!
3//! These traits are implemented using the derive macros found in `./glue_derive` and __SHOULD NOT__ be implemented manually.
4//!
5//! The crate includes the following traits:
6//! - `JsonSerializeDeserialize`: For serializing and deserializing types to and from JSON strings.
7//! - `ByteArraySerializeDeserialize`: For serializing and deserializing types to and from byte arrays.
8
9/// A trait for types that can be serialized to and deserialized from JSON format.
10///
11/// Implement using `#[derive(JsonToFromZMQ)]`.
12/// ### Methods
13/// - `into_serialized`: Serializes the implementing type to a JSON string `String`.
14/// - `try_from_serialized`: Attempts to create an instance of the implementing type from a given `String` by deserializing the JSON contained within.
15pub trait JsonSerializeDeserialize: serde::Serialize + for<'a> serde::Deserialize<'a> {
16    fn into_serialized(self) -> String {
17        serde_json::to_string(&self).expect("Failed to serialize message to JSON")
18    }
19
20    fn try_from_serialized(serialized_msg: &str) -> Result<Self, serde_json::Error> {
21        serde_json::from_str(serialized_msg)
22    }
23}
24
25/// A trait for types that can be serialized to and deserialized from byte arrays.
26///
27/// Implement using `#[derive(ByteArrayToFromZMQ)]`.
28/// ### Methods
29/// - `into_zmq_message`: Serializes the implementing type to a byte array `Vec<u8>`.
30/// - `try_from_zmq_message`: Attempts to create an instance of the implementing type from a given `Vec<u8>` by deserializing the byte array contained within.
31pub trait ByteArraySerializeDeserialize: serde::Serialize + for<'a> serde::Deserialize<'a> {
32    fn into_serialized(self) -> Vec<u8> {
33        bincode::serialize(&self).expect("Failed to serialize message to byte array")
34    }
35
36    fn try_from_serialized(serialized_msg: Vec<u8>) -> Result<Self, bincode::Error> {
37        bincode::deserialize(&serialized_msg)
38    }
39}