iceoryx2_cal/serialize/
mod.rs

1// Copyright (c) 2023 Contributors to the Eclipse Foundation
2//
3// See the NOTICE file(s) distributed with this work for additional
4// information regarding copyright ownership.
5//
6// This program and the accompanying materials are made available under the
7// terms of the Apache Software License 2.0 which is available at
8// https://www.apache.org/licenses/LICENSE-2.0, or the MIT license
9// which is available at https://opensource.org/licenses/MIT.
10//
11// SPDX-License-Identifier: Apache-2.0 OR MIT
12
13//! Simplifies the kind of serialization which shall be used. The implementation has two methods
14//!  * [`Serialize::serialize()`] - serialize a given object
15//!  * [`Serialize::deserialize()`] - deserialize a given byte reference into the source object
16//!
17//! # Example
18//!
19//! ```
20//! use serde::{Deserialize, Serialize};
21//!
22//! #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
23//! struct TestStruct {
24//!     value: u64
25//! };
26//!
27//! fn example<S: iceoryx2_cal::serialize::Serialize>() {
28//!     let data_orig = TestStruct { value: 1234 };
29//!
30//!     let serialized = S::serialize::<TestStruct>(&data_orig)
31//!                                 .expect("serialization failed.");
32//!
33//!     let data: TestStruct = S::deserialize(serialized.as_slice())
34//!                           .expect("deserialization failed.");
35//!
36//!     assert_eq!(data, data_orig);
37//! }
38//! ```
39
40pub mod cdr;
41pub mod postcard;
42pub mod recommended;
43pub mod toml;
44
45/// Failure emitted by [`Serialize::serialize()`]
46#[derive(Debug, PartialEq, Eq, Clone, Copy)]
47pub enum SerializeError {
48    InternalError,
49}
50
51/// Failure emitted by [`Serialize::deserialize()`]
52#[derive(Debug, PartialEq, Eq, Clone, Copy)]
53pub enum DeserializeError {
54    InternalError,
55}
56
57/// Serialize and deserialize constructs which implement [`serde::Serialize`] and
58/// [`serde::de::DeserializeOwned`]
59pub trait Serialize {
60    /// Serializes a value
61    fn serialize<T: serde::Serialize>(value: &T) -> Result<Vec<u8>, SerializeError>;
62
63    /// Deserialize a value from a given byte slice
64    fn deserialize<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<T, DeserializeError>;
65}