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 postcard;
41pub mod recommended;
42
43#[cfg(feature = "std")]
44pub mod toml;
45
46use core::fmt::Debug;
47
48use alloc::vec::Vec;
49
50/// Failure emitted by [`Serialize::serialize()`]
51#[derive(Debug, PartialEq, Eq, Clone, Copy)]
52pub enum SerializeError {
53 InternalError,
54}
55
56impl core::fmt::Display for SerializeError {
57 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
58 write!(f, "SerializeError::{self:?}")
59 }
60}
61
62impl core::error::Error for SerializeError {}
63
64/// Failure emitted by [`Serialize::deserialize()`]
65#[derive(Debug, PartialEq, Eq, Clone, Copy)]
66pub enum DeserializeError {
67 InternalError,
68}
69
70impl core::fmt::Display for DeserializeError {
71 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
72 write!(f, "DeserializeError::{self:?}")
73 }
74}
75
76impl core::error::Error for DeserializeError {}
77
78/// Serialize and deserialize constructs which implement [`serde::Serialize`] and
79/// [`serde::de::DeserializeOwned`]
80pub trait Serialize: Debug {
81 /// Serializes a value
82 fn serialize<T: serde::Serialize>(value: &T) -> Result<Vec<u8>, SerializeError>;
83
84 /// Deserialize a value from a given byte slice
85 fn deserialize<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<T, DeserializeError>;
86}