Skip to main content

osal_rs/traits/
byte.rs

1/***************************************************************************
2 *
3 * osal-rs
4 * Copyright (C) 2023/2026 Antonio Salsi <passy.linux@zresa.it>
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 *
18 ***************************************************************************/
19
20//! Byte conversion traits for serialization and deserialization.
21//!
22//! This module provides traits for converting types to and from byte arrays,
23//! enabling type-safe serialization for queue and communication operations.
24
25#[cfg(feature = "serde")]
26use osal_rs_serde::Serialize;
27
28#[cfg(not(feature = "serde"))]
29use crate::utils::Result;
30
31/// Trait for types that have a known byte length.
32///
33/// Used to determine the size of data structures when working with byte arrays.
34///
35/// # Examples
36///
37/// ```ignore
38/// use osal_rs::os::BytesHasLen;
39/// 
40/// let data: [u8; 4] = [1, 2, 3, 4];
41/// assert_eq!(data.len(), 4);
42/// ```
43pub trait BytesHasLen {
44    /// Returns the length in bytes.
45    ///
46    /// # Returns
47    ///
48    /// Number of bytes in the data structure
49    fn len(&self) -> usize;
50}
51
52/// Automatic implementation of `BytesHasLen` for fixed-size arrays.
53///
54/// This allows arrays of types implementing `ToBytes` to automatically
55/// report their size.
56impl<T, const N: usize> BytesHasLen for [T; N] 
57where 
58    T: Serialize + Sized {
59    fn len(&self) -> usize {
60        N
61    }
62}
63
64/// Trait for converting types to byte slices.
65///
66/// Enables serialization of structured data for transmission through
67/// queues or other byte-oriented communication channels.
68///
69/// # Examples
70///
71/// ```ignore
72/// use osal_rs::os::ToBytes;
73/// 
74/// struct SensorData {
75///     temperature: i16,
76///     humidity: u8,
77/// }
78/// 
79/// impl ToBytes for SensorData {
80///     fn to_bytes(&self) -> &[u8] {
81///         // Convert struct to bytes
82///     }
83/// }
84/// ```
85#[cfg(not(feature = "serde"))]
86pub trait Serialize {
87    /// Converts this value to a byte slice.
88    ///
89    /// # Returns
90    ///
91    /// A reference to the byte representation of this value
92    fn to_bytes(&self) -> &[u8];
93}
94
95/// Trait for deserializing types from byte slices.
96///
97/// Enables reconstruction of structured data from byte arrays received
98/// from queues or communication channels.
99///
100/// # Examples
101///
102/// ```ignore
103/// use osal_rs::os::FromBytes;
104/// use osal_rs::utils::Result;
105/// 
106/// struct SensorData {
107///     temperature: i16,
108///     humidity: u8,
109/// }
110/// 
111/// impl FromBytes for SensorData {
112///     fn from_bytes(bytes: &[u8]) -> Result<Self> {
113///         if bytes.len() < 3 {
114///             return Err(Error::InvalidParameter);
115///         }
116///         Ok(SensorData {
117///             temperature: i16::from_le_bytes([bytes[0], bytes[1]]),
118///             humidity: bytes[2],
119///         })
120///     }
121/// }
122/// ```
123#[cfg(not(feature = "serde"))]
124pub trait Deserialize: Sized
125where
126    Self: Sized {
127    /// Creates a new instance from a byte slice.
128    ///
129    /// # Parameters
130    ///
131    /// * `bytes` - The byte slice to deserialize from
132    ///
133    /// # Returns
134    ///
135    /// * `Ok(Self)` - Successfully deserialized value
136    /// * `Err(Error)` - Deserialization failed (invalid data, wrong size, etc.)
137    fn from_bytes(bytes: &[u8]) -> Result<Self>;
138}
139
140
141