bity_ic_serializer/lib.rs
1//! Module for serialization and deserialization using MessagePack format.
2//!
3//! This module provides utilities for efficiently serializing and deserializing data
4//! using the MessagePack format, which is a binary serialization format that is
5//! more compact than JSON and supports more data types.
6//!
7//! # Example
8//! ```
9//! use std::io::Cursor;
10//! use serde::{Serialize, Deserialize};
11//!
12//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
13//! struct Person {
14//! name: String,
15//! age: u32,
16//! }
17//!
18//! let person = Person {
19//! name: "Alice".to_string(),
20//! age: 30,
21//! };
22//!
23//! let mut buffer = Vec::new();
24//! serialize(&person, &mut buffer).unwrap();
25//!
26//! let deserialized: Person = deserialize(Cursor::new(&buffer)).unwrap();
27//! assert_eq!(person, deserialized);
28//! ```
29
30use serde::{de::DeserializeOwned, Serialize};
31use std::error::Error;
32use std::io::{Read, Write};
33
34/// Serializes a value into a MessagePack format using the provided writer.
35///
36/// # Arguments
37/// * `value` - The value to serialize
38/// * `writer` - The writer to write the serialized data to
39///
40/// # Returns
41/// A `Result` containing either `()` on success or an error on failure
42///
43/// # Type Parameters
44/// * `T` - The type of the value to serialize (must implement `Serialize`)
45/// * `W` - The type of the writer (must implement `Write`)
46pub fn serialize<T, W>(value: T, writer: W) -> Result<(), impl Error>
47where
48 T: Serialize,
49 W: Write,
50{
51 let mut serializer = rmp_serde::Serializer::new(writer).with_struct_map();
52 value.serialize(&mut serializer).map(|_| ())
53}
54
55/// Deserializes a value from MessagePack format using the provided reader.
56///
57/// # Arguments
58/// * `reader` - The reader to read the serialized data from
59///
60/// # Returns
61/// A `Result` containing either the deserialized value on success or an error on failure
62///
63/// # Type Parameters
64/// * `T` - The type of the value to deserialize (must implement `DeserializeOwned`)
65/// * `R` - The type of the reader (must implement `Read`)
66pub fn deserialize<T, R>(reader: R) -> Result<T, impl Error>
67where
68 T: DeserializeOwned,
69 R: Read,
70{
71 let mut deserializer = rmp_serde::Deserializer::new(reader);
72 T::deserialize(&mut deserializer)
73}