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
28use crate::utils::Result;
29
30/// Trait for types that have a known byte length.
31///
32/// Used to determine the size of data structures when working with byte arrays.
33///
34/// # Examples
35///
36/// ```ignore
37/// use osal_rs::os::BytesHasLen;
38/// 
39/// let data: [u8; 4] = [1, 2, 3, 4];
40/// assert_eq!(data.len(), 4);
41/// ```
42pub trait BytesHasLen {
43    /// Returns the length in bytes.
44    ///
45    /// # Returns
46    ///
47    /// Number of bytes in the data structure
48    fn len(&self) -> usize;
49}
50
51/// Automatic implementation of `BytesHasLen` for fixed-size arrays.
52///
53/// This allows arrays of types implementing `ToBytes` to automatically
54/// report their size.
55impl<T, const N: usize> BytesHasLen for [T; N] 
56where 
57    T: Serialize + Sized {
58    fn len(&self) -> usize {
59        N
60    }
61}
62
63/// Trait for converting types to byte slices.
64///
65/// Enables serialization of structured data for transmission through
66/// queues or other byte-oriented communication channels.
67///
68/// # Examples
69///
70/// ```ignore
71/// use osal_rs::os::ToBytes;
72/// 
73/// struct SensorData {
74///     temperature: i16,
75///     humidity: u8,
76/// }
77/// 
78/// impl ToBytes for SensorData {
79///     fn to_bytes(&self) -> &[u8] {
80///         // Convert struct to bytes
81///     }
82/// }
83/// ```
84#[cfg(not(feature = "serde"))]
85pub trait Serialize {
86    /// Converts this value to a byte slice.
87    ///
88    /// # Returns
89    ///
90    /// A reference to the byte representation of this value
91    fn to_bytes(&self) -> &[u8];
92}
93
94/// Trait for deserializing types from byte slices.
95///
96/// Enables reconstruction of structured data from byte arrays received
97/// from queues or communication channels.
98///
99/// # Examples
100///
101/// ```ignore
102/// use osal_rs::os::FromBytes;
103/// use osal_rs::utils::Result;
104/// 
105/// struct SensorData {
106///     temperature: i16,
107///     humidity: u8,
108/// }
109/// 
110/// impl FromBytes for SensorData {
111///     fn from_bytes(bytes: &[u8]) -> Result<Self> {
112///         if bytes.len() < 3 {
113///             return Err(Error::InvalidParameter);
114///         }
115///         Ok(SensorData {
116///             temperature: i16::from_le_bytes([bytes[0], bytes[1]]),
117///             humidity: bytes[2],
118///         })
119///     }
120/// }
121/// ```
122#[cfg(not(feature = "serde"))]
123pub trait Deserialize: Sized
124where
125    Self: Sized {
126    /// Creates a new instance from a byte slice.
127    ///
128    /// # Parameters
129    ///
130    /// * `bytes` - The byte slice to deserialize from
131    ///
132    /// # Returns
133    ///
134    /// * `Ok(Self)` - Successfully deserialized value
135    /// * `Err(Error)` - Deserialization failed (invalid data, wrong size, etc.)
136    fn from_bytes(bytes: &[u8]) -> Result<Self>;
137}
138
139
140