osal_rs/utils.rs
1/***************************************************************************
2 *
3 * osal-rs
4 * Copyright (C) 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//! Utility types and functions for OSAL-RS.
21//!
22//! This module contains common types, error definitions, and helper functions
23//! used throughout the library.
24//!
25//! # Overview
26//!
27//! The utilities module provides essential building blocks for working with
28//! OSAL-RS in embedded environments:
29//!
30//! - **Error handling**: Comprehensive [`Error`] enum for all OSAL operations
31//! - **String utilities**: Fixed-size [`Bytes`] type for embedded string handling
32//! - **Conversion macros**: Safe C string conversion and parameter extraction
33//! - **FFI types**: Type aliases for C interoperability
34//! - **Thread safety**: [`SyncUnsafeCell`] for static mutable state in Rust 2024+
35//!
36//! # Main Types
37//!
38//! ## Error Handling
39//!
40//! - [`Error<'a>`] - All possible error conditions with optional borrowed error messages
41//! - [`Result<T, E>`] - Type alias for `core::result::Result` with default `Error<'static>`
42//! - [`OsalRsBool`] - Boolean type compatible with RTOS return values
43//!
44//! ## String Handling
45//!
46//! - [`Bytes<SIZE>`] - Fixed-size byte buffer with string conversion utilities
47//! - [`AsSyncStr`] - Trait for thread-safe string references
48//!
49//! ## Constants
50//!
51//! - [`MAX_DELAY`] - Maximum timeout for blocking indefinitely
52//! - [`CpuRegisterSize`] - CPU register size detection (32-bit or 64-bit)
53//!
54//! ## FFI Types
55//!
56//! - [`Ptr`], [`ConstPtr`], [`DoublePtr`] - Type aliases for C pointers
57//!
58//! ## Thread Safety
59//!
60//! - [`SyncUnsafeCell<T>`] - Wrapper for static mutable variables (replaces `static mut`)
61//!
62//! # Macros
63//!
64//! ## String Conversion
65//!
66//! - [`from_c_str!`] - Convert C string pointer to Rust String (lossy conversion)
67//! - [`to_cstring!`] - Convert Rust string to CString with error handling
68//! - [`to_c_str!`] - Convert Rust string to C string pointer (panics on error)
69//! - [`from_str_to_array!`] - Convert string to fixed-size byte array
70//!
71//! ## Parameter Handling
72//!
73//! - [`thread_extract_param!`] - Extract typed parameter from thread entry point
74//! - [`access_static_option!`] - Access static Option variable (panics if None)
75//!
76//! # Helper Functions
77//!
78//! ## Hex Conversion
79//!
80//! - [`bytes_to_hex`] - Convert bytes to hex string (allocates)
81//! - [`bytes_to_hex_into_slice`] - Convert bytes to hex into buffer (no allocation)
82//! - [`hex_to_bytes`] - Parse hex string to bytes (allocates)
83//! - [`hex_to_bytes_into_slice`] - Parse hex string into buffer (no allocation)
84//!
85//! # Platform Detection
86//!
87//! - [`register_bit_size`] - Const function to detect CPU register size (32-bit or 64-bit)
88//!
89//! # Best Practices
90//!
91//! 1. **Use `Bytes<SIZE>` for embedded strings**: Avoids heap allocation, fixed size
92//! 2. **Prefer no-alloc variants**: Use `_into_slice` functions when possible
93//! 3. **Handle errors explicitly**: Always check `Result` returns
94//! 4. **Use `to_cstring!` over `to_c_str!`**: Better error handling with `?` operator
95//! 5. **Synchronize `SyncUnsafeCell` access**: Use mutexes or critical sections in multi-threaded environments
96
97use core::cell::UnsafeCell;
98use core::ffi::{CStr, c_char, c_uchar, c_void};
99use core::str::{from_utf8_mut, FromStr};
100use core::fmt::{Debug, Display};
101use core::ops::{Deref, DerefMut};
102use core::time::Duration;
103
104use alloc::format;
105use alloc::string::{String, ToString};
106use alloc::vec::Vec;
107
108#[cfg(not(feature = "serde"))]
109use crate::os::{Deserialize, Serialize};
110
111#[cfg(feature = "serde")]
112use osal_rs_serde::{Deserialize, Serialize};
113
114/// Error types for OSAL-RS operations.
115///
116/// Represents all possible error conditions that can occur when using
117/// the OSAL-RS library.
118///
119/// # Lifetime Parameter
120///
121/// The error type is generic over lifetime `'a` to allow flexible error messages.
122/// Most of the time, you can use the default [`Result<T>`] type alias which uses
123/// `Error<'static>`. For custom lifetimes in error messages, use
124/// `core::result::Result<T, Error<'a>>` explicitly.
125///
126/// # Examples
127///
128/// ## Basic usage with static errors
129///
130/// ```ignore
131/// use osal_rs::os::{Queue, QueueFn};
132/// use osal_rs::utils::Error;
133///
134/// match Queue::new(10, 32) {
135/// Ok(queue) => { /* use queue */ },
136/// Err(Error::OutOfMemory) => println!("Failed to allocate queue"),
137/// Err(e) => println!("Other error: {:?}", e),
138/// }
139/// ```
140///
141/// ## Using borrowed error messages
142///
143/// ```ignore
144/// use osal_rs::utils::Error;
145///
146/// fn validate_input(input: &str) -> core::result::Result<(), Error> {
147/// if input.is_empty() {
148/// // Use static lifetime for compile-time strings
149/// Err(Error::Unhandled("Input cannot be empty"))
150/// } else {
151/// Ok(())
152/// }
153/// }
154///
155/// // For dynamic error messages from borrowed data
156/// fn process_data<'a>(data: &'a str) -> core::result::Result<(), Error<'a>> {
157/// if !data.starts_with("valid:") {
158/// // Error message borrows from 'data' lifetime
159/// Err(Error::ReadError(data))
160/// } else {
161/// Ok(())
162/// }
163/// }
164/// ```
165#[derive(Debug, Clone, PartialEq, Eq, Hash)]
166pub enum Error<'a> {
167 /// Insufficient memory to complete operation
168 OutOfMemory,
169 /// Queue send operation timed out
170 QueueSendTimeout,
171 /// Queue receive operation timed out
172 QueueReceiveTimeout,
173 /// Mutex operation timed out
174 MutexTimeout,
175 /// Failed to acquire mutex lock
176 MutexLockFailed,
177 /// Generic timeout error
178 Timeout,
179 /// Queue is full and cannot accept more items
180 QueueFull,
181 /// String conversion failed
182 StringConversionError,
183 /// Thread/task not found
184 TaskNotFound,
185 /// Invalid queue size specified
186 InvalidQueueSize,
187 /// Null pointer encountered
188 NullPtr,
189 /// Requested item not found
190 NotFound,
191 /// Index out of bounds
192 OutOfIndex,
193 /// Invalid type for operation
194 InvalidType,
195 /// No data available
196 Empty,
197 /// Write error occurred
198 WriteError(&'a str),
199 /// Read error occurred
200 ReadError(&'a str),
201 /// Return error with code
202 ReturnWithCode(i32),
203 /// Unhandled error with description
204 Unhandled(&'a str),
205 /// Unhandled error with description owned
206 UnhandledOwned(String)
207}
208
209impl<'a> Display for Error<'a> {
210 /// Formats the error for display.
211 ///
212 /// Provides human-readable error messages suitable for logging or
213 /// presentation to users.
214 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
215 use Error::*;
216
217 match self {
218 OutOfMemory => write!(f, "Out of memory"),
219 QueueSendTimeout => write!(f, "Queue send timeout"),
220 QueueReceiveTimeout => write!(f, "Queue receive timeout"),
221 MutexTimeout => write!(f, "Mutex timeout"),
222 MutexLockFailed => write!(f, "Mutex lock failed"),
223 Timeout => write!(f, "Operation timeout"),
224 QueueFull => write!(f, "Queue full"),
225 StringConversionError => write!(f, "String conversion error"),
226 TaskNotFound => write!(f, "Task not found"),
227 InvalidQueueSize => write!(f, "Invalid queue size"),
228 NullPtr => write!(f, "Null pointer encountered"),
229 NotFound => write!(f, "Item not found"),
230 OutOfIndex => write!(f, "Index out of bounds"),
231 InvalidType => write!(f, "Invalid type for operation"),
232 Empty => write!(f, "No data available"),
233 WriteError(desc) => write!(f, "Write error occurred: {}", desc),
234 ReadError(desc) => write!(f, "Read error occurred: {}", desc),
235 ReturnWithCode(code) => write!(f, "Return with code: {}", code),
236 Unhandled(desc) => write!(f, "Unhandled error: {}", desc),
237 UnhandledOwned(desc) => write!(f, "Unhandled error owned: {}", desc),
238 }
239 }
240}
241
242
243/// CPU register size enumeration.
244///
245/// Identifies whether the target CPU uses 32-bit or 64-bit registers.
246/// This is used for platform-specific tick count overflow handling and
247/// time calculation optimizations.
248///
249/// # Usage
250///
251/// Typically determined at compile time via [`register_bit_size()`] which
252/// checks `size_of::<usize>()`.
253///
254/// # Examples
255///
256/// ```ignore
257/// use osal_rs::utils::{CpuRegisterSize, register_bit_size};
258///
259/// match register_bit_size() {
260/// CpuRegisterSize::Bit64 => {
261/// // Use 64-bit optimized calculations
262/// }
263/// CpuRegisterSize::Bit32 => {
264/// // Use 32-bit overflow-safe calculations
265/// }
266/// }
267/// ```
268#[derive(PartialEq, Eq, Clone, Copy, Debug)]
269pub enum CpuRegisterSize {
270 /// 64-bit CPU registers (e.g., ARM Cortex-A, x86_64).
271 ///
272 /// On these platforms, `usize` is 8 bytes.
273 Bit64,
274
275 /// 32-bit CPU registers (e.g., ARM Cortex-M, RP2040, ESP32).
276 ///
277 /// On these platforms, `usize` is 4 bytes.
278 Bit32
279}
280
281/// Boolean type compatible with RTOS return values.
282///
283/// Many RTOS functions return 0 for success and non-zero for failure.
284/// This type provides a Rust-idiomatic way to work with such values.
285///
286/// # Examples
287///
288/// ```ignore
289/// use osal_rs::os::{Semaphore, SemaphoreFn};
290/// use osal_rs::utils::OsalRsBool;
291/// use core::time::Duration;
292///
293/// let sem = Semaphore::new(1, 1).unwrap();
294///
295/// match sem.wait(Duration::from_millis(100)) {
296/// OsalRsBool::True => println!("Acquired semaphore"),
297/// OsalRsBool::False => println!("Failed to acquire"),
298/// }
299///
300/// // Can also convert to bool
301/// if sem.signal().into() {
302/// println!("Semaphore signaled");
303/// }
304/// ```
305#[derive(PartialEq, Eq, Clone, Copy, Debug)]
306#[repr(u8)]
307pub enum OsalRsBool {
308 /// Operation failed or condition is false
309 False = 1,
310 /// Operation succeeded or condition is true
311 True = 0
312}
313
314/// Maximum delay constant for blocking operations.
315///
316/// When used as a timeout parameter, indicates the operation should
317/// block indefinitely until it succeeds.
318///
319/// # Examples
320///
321/// ```ignore
322/// use osal_rs::os::{Mutex, MutexFn};
323/// use osal_rs::utils::MAX_DELAY;
324///
325/// let mutex = Mutex::new(0);
326/// let guard = mutex.lock(); // Blocks forever if needed
327/// ```
328pub const MAX_DELAY: Duration = Duration::from_millis(usize::MAX as u64);
329
330/// Standard Result type for OSAL-RS operations.
331///
332/// Uses [`Error`] as the default error type with `'static` lifetime.
333/// For custom lifetimes, use `core::result::Result<T, Error<'a>>`.
334///
335/// # Examples
336///
337/// ```ignore
338/// use osal_rs::utils::Result;
339///
340/// fn create_resource() -> Result<ResourceHandle> {
341/// // Returns Result<ResourceHandle, Error<'static>>
342/// Ok(ResourceHandle::new())
343/// }
344/// ```
345pub type Result<T, E = Error<'static>> = core::result::Result<T, E>;
346
347/// Pointer to pointer type for C FFI.
348///
349/// Equivalent to `void**` in C. Used for double indirection in FFI calls.
350pub type DoublePtr = *mut *mut c_void;
351
352/// Mutable pointer type for C FFI.
353///
354/// Equivalent to `void*` in C. Used for generic mutable data pointers.
355pub type Ptr = *mut c_void;
356
357/// Const pointer type for C FFI.
358///
359/// Equivalent to `const void*` in C. Used for generic immutable data pointers.
360pub type ConstPtr = *const c_void;
361
362
363/// Determines the CPU register size at compile time.
364///
365/// This constant function checks the size of `usize` to determine whether
366/// the target architecture uses 32-bit or 64-bit registers. This information
367/// is used for platform-specific optimizations and overflow handling.
368///
369/// # Returns
370///
371/// * [`CpuRegisterSize::Bit64`] - For 64-bit architectures
372/// * [`CpuRegisterSize::Bit32`] - For 32-bit architectures
373///
374/// # Examples
375///
376/// ```ignore
377/// use osal_rs::utils::{register_bit_size, CpuRegisterSize};
378///
379/// match register_bit_size() {
380/// CpuRegisterSize::Bit64 => println!("Running on 64-bit platform"),
381/// CpuRegisterSize::Bit32 => println!("Running on 32-bit platform"),
382/// }
383/// ```
384pub const fn register_bit_size() -> CpuRegisterSize {
385 if size_of::<usize>() == 8 {
386 CpuRegisterSize::Bit64
387 } else {
388 CpuRegisterSize::Bit32
389 }
390}
391
392/// Converts a C string pointer to a Rust String.
393///
394/// This macro safely converts a raw C string pointer (`*const c_char`) into
395/// a Rust `String`. It handles UTF-8 conversion gracefully using lossy conversion.
396///
397/// # Safety
398///
399/// The pointer must be valid and point to a null-terminated C string.
400///
401/// # Examples
402///
403/// ```ignore
404/// use osal_rs::from_c_str;
405/// use core::ffi::c_char;
406///
407/// extern "C" {
408/// fn get_system_name() -> *const c_char;
409/// }
410///
411/// let name = from_c_str!(get_system_name());
412/// println!("System: {}", name);
413/// ```
414#[macro_export]
415macro_rules! from_c_str {
416 ($str:expr) => {
417 unsafe {
418 let c_str = core::ffi::CStr::from_ptr($str);
419 alloc::string::String::from_utf8_lossy(c_str.to_bytes()).to_string()
420 }
421 };
422}
423
424/// Converts a Rust string to a CString with error handling.
425///
426/// This macro creates a `CString` from a Rust string reference, returning
427/// a `Result` that can be used with the `?` operator. If the conversion fails
428/// (e.g., due to interior null bytes), it returns an appropriate error.
429///
430/// # Returns
431///
432/// * `Ok(CString)` - On successful conversion
433/// * `Err(Error::Unhandled)` - If the string contains interior null bytes
434///
435/// # Examples
436///
437/// ```ignore
438/// use osal_rs::to_cstring;
439/// use osal_rs::utils::Result;
440///
441/// fn pass_to_c_api(name: &str) -> Result<()> {
442/// let c_name = to_cstring!(name)?;
443/// // Use c_name.as_ptr() with C FFI
444/// Ok(())
445/// }
446/// ```
447#[macro_export]
448macro_rules! to_cstring {
449 ($s:expr) => {
450 alloc::ffi::CString::new($s.as_str())
451 .map_err(|_| $crate::utils::Error::Unhandled("Failed to convert string to CString"))
452 };
453}
454
455/// Converts a Rust string to a C string pointer.
456///
457/// This macro creates a `CString` from a Rust string and returns its raw pointer.
458/// **Warning**: This macro panics if the conversion fails. Consider using
459/// [`to_cstring!`] for safer error handling.
460///
461/// # Panics
462///
463/// Panics if the string contains interior null bytes.
464///
465/// # Examples
466///
467/// ```ignore
468/// use osal_rs::to_c_str;
469///
470/// extern "C" {
471/// fn set_name(name: *const core::ffi::c_char);
472/// }
473///
474/// let name = "FreeRTOS Task";
475/// unsafe {
476/// set_name(to_c_str!(name));
477/// }
478/// ```
479#[macro_export]
480macro_rules! to_c_str {
481 ($s:expr) => {
482 alloc::ffi::CString::new($s.as_ref() as &str).unwrap().as_ptr()
483 };
484}
485
486/// Converts a string to a fixed-size byte array.
487///
488/// This macro creates a byte array of the specified size and fills it with
489/// the bytes from the input string. If the string is shorter than the buffer,
490/// the remaining bytes are filled with spaces. If the string is longer, it
491/// is truncated to fit.
492///
493/// # Parameters
494///
495/// * `$str` - The source string to convert
496/// * `$buff_name` - The identifier name for the created buffer variable
497/// * `$buff_size` - The size of the byte array to create
498///
499/// # Examples
500///
501/// ```ignore
502/// use osal_rs::from_str_to_array;
503///
504/// let task_name = "MainTask";
505/// from_str_to_array!(task_name, name_buffer, 16);
506/// // name_buffer is now [u8; 16] containing "MainTask "
507///
508/// // Use with C FFI
509/// extern "C" {
510/// fn create_task(name: *const u8, len: usize);
511/// }
512///
513/// unsafe {
514/// create_task(name_buffer.as_ptr(), name_buffer.len());
515/// }
516/// ```
517#[macro_export]
518macro_rules! from_str_to_array {
519 ($str:expr, $buff_name:ident, $buff_size:expr) => {
520 let mut $buff_name = [b' '; $buff_size];
521 let _bytes = $str.as_bytes();
522 let _len = core::cmp::min(_bytes.len(), $buff_size);
523 $buff_name[.._len].copy_from_slice(&_bytes[.._len]);
524 };
525}
526
527/// Extracts a typed parameter from an optional boxed Any reference.
528///
529/// This macro is used in thread/task entry points to safely extract and
530/// downcast parameters passed to the thread. It handles both the Option
531/// unwrapping and the type downcast, returning appropriate errors if either
532/// operation fails.
533///
534/// # Parameters
535///
536/// * `$param` - An `Option<Box<dyn Any>>` containing the parameter
537/// * `$t` - The type to downcast the parameter to
538///
539/// # Returns
540///
541/// * A reference to the downcasted value of type `$t`
542/// * `Err(Error::NullPtr)` - If the parameter is None
543/// * `Err(Error::InvalidType)` - If the downcast fails
544///
545/// # Examples
546///
547/// ```ignore
548/// use osal_rs::thread_extract_param;
549/// use osal_rs::utils::Result;
550/// use core::any::Any;
551///
552/// struct TaskConfig {
553/// priority: u8,
554/// stack_size: usize,
555/// }
556///
557/// fn task_entry(param: Option<Box<dyn Any>>) -> Result<()> {
558/// let config = thread_extract_param!(param, TaskConfig);
559///
560/// println!("Priority: {}", config.priority);
561/// println!("Stack: {}", config.stack_size);
562///
563/// Ok(())
564/// }
565/// ```
566#[macro_export]
567macro_rules! thread_extract_param {
568 ($param:expr, $t:ty) => {
569 match $param.as_ref() {
570 Some(p) => {
571 match p.downcast_ref::<$t>() {
572 Some(value) => value,
573 None => return Err($crate::utils::Error::InvalidType),
574 }
575 }
576 None => return Err($crate::utils::Error::NullPtr),
577 }
578 };
579}
580
581/// Accesses a static Option variable, returning the contained value or panicking if None.
582///
583/// This macro is used to safely access static variables that are initialized at runtime.
584/// It checks if the static variable is `Some` and returns the contained value. If the variable
585/// is `None`, it panics with a message indicating that the variable is not initialized.
586///
587/// # Parameters
588/// * `$static_var` - The identifier of the static variable to access
589/// # Returns
590/// * The value contained in the static variable if it is `Some`
591/// * Panics if the static variable is `None`, with a message indicating it is not initialized
592/// # Examples
593/// ```ignore
594/// use osal_rs::access_static_option;
595/// static mut CONFIG: Option<Config> = None;
596/// fn get_config() -> &'static Config {
597/// access_static_option!(CONFIG)
598/// }
599/// ```
600///
601/// Note: This macro assumes that the static variable is of type `Option<T>` and that it is initialized at runtime before being accessed. It is intended for use with static variables that are set up during initialization phases of the program, such as in embedded systems where certain resources are not available at compile time.
602///
603/// # Safety
604/// This macro uses unsafe code to access the static variable. It is the caller's responsibility to ensure that the static variable is properly initialized before it is accessed, and that it is not accessed concurrently from multiple threads without proper synchronization.
605/// # Warning
606/// This macro will panic if the static variable is not initialized (i.e., if it is `None`). It should be used in contexts where it is guaranteed that the variable will be initialized before
607/// accessing it, such as after an initialization function has been called.
608/// # Alternative
609/// For safer access to static variables, consider using a function that returns a `Result` instead of panicking, allowing the caller to handle the error condition gracefully.
610/// ```ignore
611/// fn get_config() -> Result<&'static Config, Error> {
612/// unsafe {
613/// match &*&raw const CONFIG {
614/// Some(config) => Ok(config),
615/// None => Err(Error::Unhandled("CONFIG is not initialized")),
616/// }
617/// }
618/// }
619/// ```
620/// This alternative approach allows for error handling without panicking, which can be more appropriate in many contexts, especially in production code or libraries where robustness is important.
621/// # Note
622/// This macro is intended for use in embedded systems or low-level code where static variables are commonly used for global state or resources that are initialized at runtime. It provides a convenient way to access such
623/// variables while ensuring that they are initialized, albeit with the risk of panicking if they are not. Use with caution and ensure proper initialization to avoid runtime panics.
624#[macro_export]
625macro_rules! access_static_option {
626 ($static_var:ident) => {
627 unsafe {
628 match &*&raw const $static_var {
629 Some(value) => value,
630 None => panic!(concat!(stringify!($static_var), " is not initialized")),
631 }
632 }
633 };
634}
635
636/// Trait for types that can provide a string reference in a thread-safe manner.
637///
638/// This trait extends the basic string reference functionality with thread-safety
639/// guarantees by requiring both `Sync` and `Send` bounds. It's useful for types
640/// that need to provide string data across thread boundaries in a concurrent
641/// environment.
642///
643/// # Thread Safety
644///
645/// Implementors must be both `Sync` (safe to share references across threads) and
646/// `Send` (safe to transfer ownership across threads).
647///
648/// # Examples
649///
650/// ```ignore
651/// use osal_rs::utils::AsSyncStr;
652///
653/// struct ThreadSafeName {
654/// name: &'static str,
655/// }
656///
657/// impl AsSyncStr for ThreadSafeName {
658/// fn as_str(&self) -> &str {
659/// self.name
660/// }
661/// }
662///
663/// // Can be safely shared across threads
664/// fn use_in_thread(item: &dyn AsSyncStr) {
665/// println!("Name: {}", item.as_str());
666/// }
667/// ```
668pub trait AsSyncStr : Sync + Send {
669 /// Returns a string slice reference.
670 ///
671 /// This method provides access to the underlying string data in a way
672 /// that is safe to use across thread boundaries.
673 ///
674 /// # Returns
675 ///
676 /// A reference to a string slice with lifetime tied to `self`.
677 fn as_str(&self) -> &str;
678}
679
680impl PartialEq for dyn AsSyncStr + '_ {
681 fn eq(&self, other: &(dyn AsSyncStr + '_)) -> bool {
682 self.as_str() == other.as_str()
683 }
684}
685
686impl Eq for dyn AsSyncStr + '_ {}
687
688impl Debug for dyn AsSyncStr + '_ {
689 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
690 write!(f, "{}", self.as_str())
691 }
692}
693
694impl Display for dyn AsSyncStr + '_ {
695 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
696 write!(f, "{}", self.as_str())
697 }
698}
699
700
701/// Fixed-size byte array wrapper with string conversion utilities.
702///
703/// `Bytes` is a generic wrapper around a fixed-size byte array that provides
704/// convenient methods for converting between strings and byte arrays. It's
705/// particularly useful for interfacing with C APIs that expect fixed-size
706/// character buffers, or for storing strings in embedded systems with
707/// constrained memory.
708///
709/// # Type Parameters
710///
711/// * `SIZE` - The size of the internal byte array (default: 0)
712///
713/// # Examples
714///
715/// ```ignore
716/// use osal_rs::utils::Bytes;
717///
718/// // Create an empty 32-byte buffer
719/// let mut buffer = Bytes::<32>::new();
720///
721/// // Create a buffer from a string
722/// let name = Bytes::<16>::new_by_str("TaskName");
723/// println!("{}", name); // Prints "TaskName"
724///
725/// // Create from any type that implements ToString
726/// let number = 42;
727/// let num_bytes = Bytes::<8>::new_by_string(&number);
728/// ```
729#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
730pub struct Bytes<const SIZE: usize> (pub [u8; SIZE]);
731
732impl<const SIZE: usize> Deref for Bytes<SIZE> {
733 type Target = [u8; SIZE];
734
735 /// Dereferences to the underlying byte array.
736 ///
737 /// This allows `Bytes` to be used anywhere a `[u8; SIZE]` reference is expected.
738 ///
739 /// # Examples
740 ///
741 /// ```ignore
742 /// use osal_rs::utils::Bytes;
743 ///
744 /// let bytes = Bytes::<8>::new_by_str("test");
745 /// assert_eq!(bytes[0], b't');
746 /// ```
747 fn deref(&self) -> &Self::Target {
748 &self.0
749 }
750}
751
752impl<const SIZE: usize> DerefMut for Bytes<SIZE> {
753 /// Provides mutable access to the underlying byte array.
754 ///
755 /// This allows `Bytes` to be mutably dereferenced, enabling direct modification
756 /// of the internal byte array through the `DerefMut` trait.
757 ///
758 /// # Examples
759 ///
760 /// ```ignore
761 /// use osal_rs::utils::Bytes;
762 ///
763 /// let mut bytes = Bytes::<8>::new();
764 /// bytes[0] = b'H';
765 /// bytes[1] = b'i';
766 /// assert_eq!(bytes[0], b'H');
767 /// ```
768 fn deref_mut(&mut self) -> &mut Self::Target {
769 &mut self.0
770 }
771}
772
773impl<const SIZE: usize> Display for Bytes<SIZE> {
774 /// Formats the byte array as a C-style null-terminated string.
775 ///
776 /// This implementation treats the byte array as a C string and converts it
777 /// to a Rust string for display. If the conversion fails, it displays
778 /// "Conversion error".
779 ///
780 /// # Safety
781 ///
782 /// This method assumes the byte array contains valid UTF-8 data and is
783 /// null-terminated. Invalid data may result in the error message being displayed.
784 ///
785 /// # Examples
786 ///
787 /// ```ignore
788 /// use osal_rs::utils::Bytes;
789 ///
790 /// let bytes = Bytes::<16>::new_by_str("Hello");
791 /// println!("{}", bytes); // Prints "Hello"
792 /// ```
793 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
794 let str = unsafe {
795 CStr::from_ptr(self.0.as_ptr() as *const c_char)
796 .to_str()
797 .unwrap_or("Conversion error")
798 };
799
800 write!(f, "{}", str.to_string())
801 }
802}
803
804impl<const SIZE: usize> FromStr for Bytes<SIZE> {
805 type Err = Error<'static>;
806
807 /// Creates a `Bytes` instance from a string slice.
808 ///
809 /// This implementation allows for easy conversion from string literals or
810 /// string slices to the `Bytes` type, filling the internal byte array
811 /// with the string data and padding with spaces if necessary.
812 ///
813 /// # Examples
814 //// ```ignore
815 /// use osal_rs::utils::Bytes;
816 ///
817 /// let bytes: Bytes<16> = "Hello".parse().unwrap();
818 /// println!("{}", bytes); // Prints "Hello"
819 /// ```
820 #[inline]
821 fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
822 Ok(Self::from_str(s))
823 }
824}
825
826impl<const SIZE: usize> From<&str> for Bytes<SIZE> {
827 /// Creates a `Bytes` instance from a string slice.
828 ///
829 /// This implementation allows for easy conversion from string literals or
830 /// string slices to the `Bytes` type, filling the internal byte array
831 /// with the string data and padding with spaces if necessary.
832 ///
833 /// # Examples
834 ///
835 /// ```ignore
836 /// use osal_rs::utils::Bytes;
837 ///
838 /// let bytes: Bytes<16> = "Hello".into();
839 /// println!("{}", bytes); // Prints "Hello"
840 /// ```
841 #[inline]
842 fn from(s: &str) -> Self {
843 Self::from_str(s)
844 }
845}
846
847impl<const SIZE: usize> AsSyncStr for Bytes<SIZE> {
848 /// Returns a string slice reference.
849 ///
850 /// This method provides access to the underlying string data in a way
851 /// that is safe to use across thread boundaries.
852 ///
853 /// # Returns
854 ///
855 /// A reference to a string slice with lifetime tied to `self`.
856 fn as_str(&self) -> &str {
857 unsafe {
858 CStr::from_ptr(self.0.as_ptr() as *const c_char)
859 .to_str()
860 .unwrap_or("Conversion error")
861 }
862 }
863}
864
865/// Serialization implementation for `Bytes<SIZE>` when the `serde` feature is enabled.
866///
867/// This implementation provides serialization by directly serializing each byte
868/// in the array using the osal-rs-serde serialization framework.
869#[cfg(feature = "serde")]
870impl<const SIZE: usize> Serialize for Bytes<SIZE> {
871 /// Serializes the `Bytes` instance using the given serializer.
872 ///
873 /// # Parameters
874 ///
875 /// * `serializer` - The serializer to use
876 ///
877 /// # Returns
878 ///
879 /// * `Ok(())` - On successful serialization
880 /// * `Err(S::Error)` - If serialization fails
881 fn serialize<S: osal_rs_serde::Serializer>(&self, name: &str, serializer: &mut S) -> core::result::Result<(), S::Error> {
882 // Find the actual length (up to first null byte or SIZE)
883 let len = self.0.iter().position(|&b| b == 0).unwrap_or(SIZE);
884
885 // Try to serialize as UTF-8 string if valid, otherwise as hex
886 if let Ok(s) = core::str::from_utf8(&self.0[..len]) {
887 serializer.serialize_str(name, s)
888 } else {
889 // For binary data, serialize as bytes (hex encoded)
890 serializer.serialize_bytes(name, &self.0[..len])
891 }
892 }
893}
894
895/// Deserialization implementation for `Bytes<SIZE>` when the `serde` feature is enabled.
896///
897/// This implementation provides deserialization by reading bytes from the deserializer
898/// into a fixed-size array using the osal-rs-serde deserialization framework.
899#[cfg(feature = "serde")]
900impl<const SIZE: usize> Deserialize for Bytes<SIZE> {
901 /// Deserializes a `Bytes` instance using the given deserializer.
902 ///
903 /// # Parameters
904 ///
905 /// * `deserializer` - The deserializer to use
906 ///
907 /// # Returns
908 ///
909 /// * `Ok(Bytes<SIZE>)` - A new `Bytes` instance with deserialized data
910 /// * `Err(D::Error)` - If deserialization fails
911 fn deserialize<D: osal_rs_serde::Deserializer>(deserializer: &mut D, name: &str) -> core::result::Result<Self, D::Error> {
912 let mut array = [0u8; SIZE];
913 let _ = deserializer.deserialize_bytes(name, &mut array)?;
914 Ok(Self(array))
915 }
916}
917
918/// Serialization implementation for `Bytes<SIZE>` when the `serde` feature is disabled.
919///
920/// This implementation provides basic serialization by directly returning a reference
921/// to the underlying byte array. It's used when the library is compiled without the
922/// `serde` feature, providing a lightweight alternative serialization mechanism.
923#[cfg(not(feature = "serde"))]
924impl<const SIZE: usize> Serialize for Bytes<SIZE> {
925 /// Converts the `Bytes` instance to a byte slice.
926 ///
927 /// # Returns
928 ///
929 /// A reference to the internal byte array.
930 fn to_bytes(&self) -> &[u8] {
931 &self.0
932 }
933}
934
935/// Deserialization implementation for `Bytes<SIZE>` when the `serde` feature is disabled.
936///
937/// This implementation provides basic deserialization by copying bytes from a slice
938/// into a fixed-size array. If the source slice is shorter than `SIZE`, the remaining
939/// bytes are zero-filled. If longer, it's truncated to fit.
940#[cfg(not(feature = "serde"))]
941impl<const SIZE: usize> Deserialize for Bytes<SIZE> {
942 /// Creates a `Bytes` instance from a byte slice.
943 ///
944 /// # Parameters
945 ///
946 /// * `bytes` - The source byte slice to deserialize from
947 ///
948 /// # Returns
949 ///
950 /// * `Ok(Bytes<SIZE>)` - A new `Bytes` instance with data copied from the slice
951 ///
952 /// # Examples
953 ///
954 /// ```ignore
955 /// use osal_rs::utils::Bytes;
956 /// use osal_rs::os::Deserialize;
957 ///
958 /// let data = b"Hello";
959 /// let bytes = Bytes::<16>::from_bytes(data).unwrap();
960 /// // Result: [b'H', b'e', b'l', b'l', b'o', 0, 0, 0, ...]
961 /// ```
962 fn from_bytes(bytes: &[u8]) -> Result<Self> {
963 let mut array = [0u8; SIZE];
964 let len = core::cmp::min(bytes.len(), SIZE);
965 array[..len].copy_from_slice(&bytes[..len]);
966 Ok(Self( array ))
967 }
968}
969
970impl<const SIZE: usize> Bytes<SIZE> {
971 /// Creates a new `Bytes` instance filled with zeros.
972 ///
973 /// This is a const function, allowing it to be used in const contexts
974 /// and static variable declarations.
975 ///
976 /// # Returns
977 ///
978 /// A `Bytes` instance with all bytes set to 0.
979 ///
980 /// # Examples
981 ///
982 /// ```ignore
983 /// use osal_rs::utils::Bytes;
984 ///
985 /// const BUFFER: Bytes<64> = Bytes::new();
986 ///
987 /// let runtime_buffer = Bytes::<32>::new();
988 /// assert_eq!(runtime_buffer[0], 0);
989 /// ```
990 #[inline]
991 pub const fn new() -> Self {
992 Self( [0u8; SIZE] )
993 }
994
995 /// Creates a new `Bytes` instance from a string slice.
996 ///
997 /// Copies the bytes from the input string into the fixed-size array.
998 /// If the string is shorter than `SIZE`, the remaining bytes are zero-filled.
999 /// If the string is longer, it is truncated to fit.
1000 ///
1001 /// # Parameters
1002 ///
1003 /// * `str` - The source string to convert
1004 ///
1005 /// # Returns
1006 ///
1007 /// A `Bytes` instance containing the string data.
1008 ///
1009 /// # Examples
1010 ///
1011 /// ```ignore
1012 /// use osal_rs::utils::Bytes;
1013 ///
1014 /// let short = Bytes::<16>::new_by_str("Hi");
1015 /// // Internal array: [b'H', b'i', 0, 0, 0, ...]
1016 ///
1017 /// let exact = Bytes::<5>::new_by_str("Hello");
1018 /// // Internal array: [b'H', b'e', b'l', b'l', b'o']
1019 ///
1020 /// let long = Bytes::<3>::new_by_str("Hello");
1021 /// // Internal array: [b'H', b'e', b'l'] (truncated)
1022 /// ```
1023 pub fn from_str(str: &str) -> Self {
1024
1025 let mut array = [0u8; SIZE];
1026
1027 let mut i = 0usize ;
1028 for byte in str.as_bytes() {
1029 if i > SIZE - 1{
1030 break;
1031 }
1032 array[i] = *byte;
1033 i += 1;
1034 }
1035
1036 Self( array )
1037 }
1038
1039 /// Creates a new `Bytes` instance from a C string pointer.
1040 ///
1041 /// Safely converts a null-terminated C string pointer into a `Bytes` instance.
1042 /// If the pointer is null, returns a zero-initialized `Bytes`. The function
1043 /// copies bytes from the C string into the fixed-size array, truncating if
1044 /// the source is longer than `SIZE`.
1045 ///
1046 /// # Parameters
1047 ///
1048 /// * `ptr` - A pointer to a null-terminated C string (`*const c_char`)
1049 ///
1050 /// # Safety
1051 ///
1052 /// While this function is not marked unsafe, it internally uses `unsafe` code
1053 /// to dereference the pointer. The caller must ensure that:
1054 /// - If not null, the pointer points to a valid null-terminated C string
1055 /// - The memory the pointer references remains valid for the duration of the call
1056 ///
1057 /// # Returns
1058 ///
1059 /// A `Bytes` instance containing the C string data, or zero-initialized if the pointer is null.
1060 ///
1061 /// # Examples
1062 ///
1063 /// ```ignore
1064 /// use osal_rs::utils::Bytes;
1065 /// use core::ffi::c_char;
1066 /// use alloc::ffi::CString;
1067 ///
1068 /// // From a CString
1069 /// let c_string = CString::new("Hello").unwrap();
1070 /// let bytes = Bytes::<16>::new_by_ptr(c_string.as_ptr());
1071 ///
1072 /// // From a null pointer
1073 /// let null_bytes = Bytes::<16>::new_by_ptr(core::ptr::null());
1074 /// // Returns zero-initialized Bytes
1075 ///
1076 /// // Truncation example
1077 /// let long_string = CString::new("This is a very long string").unwrap();
1078 /// let short_bytes = Bytes::<8>::new_by_ptr(long_string.as_ptr());
1079 /// // Only first 8 bytes are copied
1080 /// ```
1081 pub fn from_char_ptr(ptr: *const c_char) -> Self {
1082 if ptr.is_null() {
1083 return Self::new();
1084 }
1085
1086 let mut array = [0u8; SIZE];
1087
1088 let mut i = 0usize ;
1089 for byte in unsafe { CStr::from_ptr(ptr) }.to_bytes() {
1090 if i > SIZE - 1{
1091 break;
1092 }
1093 array[i] = *byte;
1094 i += 1;
1095 }
1096
1097 Self( array )
1098 }
1099
1100
1101 /// Creates a new `Bytes` instance from a C unsigned char pointer.
1102 ///
1103 /// Safely converts a pointer to an array of unsigned chars into a `Bytes` instance. If the pointer is null, returns a zero-initialized `Bytes`. The function copies bytes from the source pointer into the fixed-size array, truncating if the source is longer than `SIZE`.
1104 ///
1105 /// # Parameters
1106 /// * `ptr` - A pointer to an array of unsigned chars (`*const c_uchar`)
1107 ///
1108 /// # Safety
1109 /// While this function is not marked unsafe, it internally uses `unsafe` code to dereference the pointer. The caller must ensure that:
1110 /// - If not null, the pointer points to a valid array of unsigned chars with at least `SIZE` bytes
1111 /// - The memory the pointer references remains valid for the duration of the call
1112 ///
1113 /// # Returns
1114 /// A `Bytes` instance containing the data from the source pointer, or zero-initialized if the pointer is null.
1115 ///
1116 /// # Examples
1117 /// ```ignore
1118 /// use osal_rs::utils::Bytes;
1119 /// use core::ffi::c_uchar;
1120 /// use alloc::ffi::CString;
1121 ///
1122 /// // From a C unsigned char pointer
1123 /// let data = [b'H', b'e', b'l', b'l', b'o', 0];
1124 /// let bytes = Bytes::<16>::from_uchar_ptr(data.as_ptr());
1125 ///
1126 /// // From a null pointer
1127 /// let null_bytes = Bytes::<16>::from_uchar_ptr(core::ptr::null());
1128 /// // Returns zero-initialized Bytes
1129 ///
1130 /// // Truncation example
1131 /// let long_data = [b'T', b'h', b'i', b's', b' ', b'i', b's', b' ', b'v', b'e', b'r', b'y', b' ', b'l', b'o', b'n', b'g', 0];
1132 /// let short_bytes = Bytes::<8>::from_uchar_ptr(long_data.as_ptr());
1133 /// // Only first 8 bytes are copied
1134 /// ```
1135 pub fn from_uchar_ptr(ptr: *const c_uchar) -> Self {
1136 if ptr.is_null() {
1137 return Self::new();
1138 }
1139
1140 let mut array = [0u8; SIZE];
1141
1142 let mut i = 0usize ;
1143 for byte in unsafe { core::slice::from_raw_parts(ptr, SIZE) } {
1144 if i > SIZE - 1{
1145 break;
1146 }
1147 array[i] = *byte;
1148 i += 1;
1149 }
1150
1151 Self( array )
1152 }
1153
1154 /// Creates a new `Bytes` instance from any type implementing `ToString`.
1155 ///
1156 /// This is a convenience wrapper around [`new_by_str`](Self::new_by_str)
1157 /// that first converts the input to a string.
1158 ///
1159 /// # Parameters
1160 ///
1161 /// * `str` - Any value that implements `ToString`
1162 ///
1163 /// # Returns
1164 ///
1165 /// A `Bytes` instance containing the string representation of the input.
1166 ///
1167 /// # Examples
1168 ///
1169 /// ```ignore
1170 /// use osal_rs::utils::Bytes;
1171 ///
1172 /// // From integer
1173 /// let num_bytes = Bytes::<8>::new_by_string(&42);
1174 ///
1175 /// // From String
1176 /// let string = String::from("Task");
1177 /// let str_bytes = Bytes::<16>::new_by_string(&string);
1178 ///
1179 /// // From custom type with ToString
1180 /// #[derive(Debug)]
1181 /// struct TaskId(u32);
1182 /// impl ToString for TaskId {
1183 /// fn to_string(&self) -> String {
1184 /// format!("Task-{}", self.0)
1185 /// }
1186 /// }
1187 /// let task_bytes = Bytes::<16>::new_by_string(&TaskId(5));
1188 /// ```
1189 #[inline]
1190 pub fn from_as_sync_str(str: &impl ToString) -> Self {
1191 Self::from_str(&str.to_string())
1192 }
1193
1194 /// Creates a new `Bytes` instance from a byte slice.
1195 ///
1196 /// This function copies bytes from the input slice into the fixed-size array. If the slice is shorter than `SIZE`, the remaining bytes are zero-filled. If the slice is longer, it is truncated to fit.
1197 ///
1198 /// # Parameters
1199 /// * `bytes` - The source byte slice to convert
1200 ///
1201 /// # Returns
1202 /// A `Bytes` instance containing the data from the byte slice.
1203 ///
1204 /// # Examples
1205 /// ```ignore
1206 /// use osal_rs::utils::Bytes;
1207 ///
1208 /// let data = b"Hello";
1209 /// let bytes = Bytes::<16>::from_bytes(data);
1210 /// // Result: [b'H', b'e', b'l', b'l', b'o', 0, 0, 0, ...]
1211 /// ```
1212 pub fn from_bytes(bytes: &[u8]) -> Self {
1213 let mut array = [0u8; SIZE];
1214 let len = core::cmp::min(bytes.len(), SIZE);
1215 array[..len].copy_from_slice(&bytes[..len]);
1216 Self( array )
1217 }
1218
1219 /// Fills a mutable string slice with the contents of the byte array.
1220 ///
1221 /// Attempts to convert the internal byte array to a UTF-8 string and
1222 /// copies it into the destination string slice. Only copies up to the
1223 /// minimum of the source and destination lengths.
1224 ///
1225 /// # Parameters
1226 ///
1227 /// * `dest` - The destination string slice to fill
1228 ///
1229 /// # Returns
1230 ///
1231 /// `Ok(())` if the operation succeeds, or `Err(Error::StringConversionError)` if the byte array cannot be converted to a valid UTF-8 string.
1232 ///
1233 /// # Examples
1234 ///
1235 /// ```ignore
1236 /// use osal_rs::utils::Bytes;
1237 ///
1238 /// let bytes = Bytes::<16>::new_by_str("Hello World");
1239 ///
1240 /// let mut output = String::from(" "); // 16 spaces
1241 /// bytes.fill_str(unsafe { output.as_mut_str() });
1242 ///
1243 /// assert_eq!(&output[..11], "Hello World");
1244 /// ```
1245 pub fn fill_str(&mut self, dest: &mut str) -> Result<()>{
1246 match from_utf8_mut(&mut self.0) {
1247 Ok(str) => {
1248 let len = core::cmp::min(str.len(), dest.len());
1249 unsafe {
1250 dest.as_bytes_mut()[..len].copy_from_slice(&str.as_bytes()[..len]);
1251 }
1252 Ok(())
1253 }
1254 Err(_) => Err(Error::StringConversionError),
1255 }
1256 }
1257
1258 /// Creates a new `Bytes` instance from a C string pointer.
1259 ///
1260 /// This is a convenience wrapper around [`new_by_ptr`](Self::new_by_ptr) that directly converts a C string pointer to a `Bytes` instance.
1261 /// If the pointer is null, it returns a zero-initialized `Bytes`. The function copies bytes from the C string into the fixed-size array, truncating if the source is longer than `SIZE`.
1262 ///
1263 /// # Parameters
1264 ///
1265 /// * `str` - A pointer to a null-terminated C string (`*const c_char`)
1266 ///
1267 /// # Safety
1268 ///
1269 /// This method uses `unsafe` code to dereference the pointer. The caller must ensure that:
1270 /// - If not null, the pointer points to a valid null-terminated C string
1271 /// - The memory the pointer references remains valid for the duration of the call
1272 ///
1273 /// - The byte array can be safely interpreted as UTF-8 if the conversion is expected to succeed. If the byte array contains invalid UTF-8, the resulting `Bytes` instance will contain the raw bytes, and the `Display` implementation will show "Conversion error" when attempting to display it as a string.
1274 ///
1275 /// # Returns
1276 ///
1277 /// A `Bytes` instance containing the C string data, or zero-initialized if the pointer is null.
1278 ///
1279 /// # Examples
1280 ///
1281 /// ```ignore
1282 /// use osal_rs::utils::Bytes;
1283 /// use core::ffi::c_char;
1284 /// use alloc::ffi::CString;
1285 ///
1286 /// // From a CString
1287 /// let c_string = CString::new("Hello").unwrap();
1288 /// let bytes = Bytes::<16>::from_cstr(c_string.as_ptr());
1289 ///
1290 /// // From a null pointer
1291 /// let null_bytes = Bytes::<16>::from_cstr(core::ptr::null());
1292 /// // Returns zero-initialized Bytes
1293 ///
1294 /// // Truncation example
1295 /// let long_string = CString::new("This is a very long string").unwrap();
1296 /// let short_bytes = Bytes::<8>::from_cstr(long_string.as_ptr());
1297 /// // Only first 8 bytes are copied
1298 /// ```
1299 #[inline]
1300 pub fn from_cstr(str: *const c_char) -> Self {
1301 Self::from_bytes(unsafe { CStr::from_ptr(str) }.to_bytes())
1302 }
1303
1304 /// Converts the byte array to a C string reference.
1305 ///
1306 /// Creates a `CStr` reference from the internal byte array, treating it as
1307 /// a null-terminated C string. This is useful for passing strings to C FFI
1308 /// functions that expect `*const c_char` or `&CStr`.
1309 ///
1310 /// # Safety
1311 ///
1312 /// This method assumes the byte array is already null-terminated. All
1313 /// constructors (`new()`, `from_str()`, `from_char_ptr()`, etc.) guarantee
1314 /// this property by initializing with `[0u8; SIZE]`.
1315 ///
1316 /// However, if you've manually modified the array via `DerefMut`,
1317 /// you must ensure the last byte remains 0.
1318 ///
1319 /// # Returns
1320 ///
1321 /// A reference to a `CStr` with lifetime tied to `self`.
1322 ///
1323 /// # Examples
1324 ///
1325 /// ```ignore
1326 /// use osal_rs::utils::Bytes;
1327 ///
1328 /// let bytes = Bytes::<16>::new_by_str("Hello");
1329 /// let c_str = bytes.as_cstr();
1330 ///
1331 /// extern "C" {
1332 /// fn print_string(s: *const core::ffi::c_char);
1333 /// }
1334 ///
1335 /// unsafe {
1336 /// print_string(c_str.as_ptr());
1337 /// }
1338 /// ```
1339 #[inline]
1340 pub fn as_cstr(&self) -> &CStr {
1341 unsafe {
1342 CStr::from_ptr(self.0.as_ptr() as *const c_char)
1343 }
1344 }
1345
1346 /// Converts the byte array to a C string reference, ensuring null-termination.
1347 ///
1348 /// This is a safer version of `as_cstr()` that explicitly guarantees
1349 /// null-termination by modifying the last byte. Use this if you've
1350 /// manually modified the array and want to ensure it's null-terminated.
1351 ///
1352 /// # Returns
1353 ///
1354 /// A reference to a `CStr` with lifetime tied to `self`.
1355 ///
1356 /// # Examples
1357 ///
1358 /// ```ignore
1359 /// use osal_rs::utils::Bytes;
1360 ///
1361 /// let mut bytes = Bytes::<16>::new();
1362 /// bytes[0] = b'H';
1363 /// bytes[1] = b'i';
1364 /// // After manual modification, ensure null-termination
1365 /// let c_str = bytes.as_cstr_mut();
1366 /// ```
1367 #[inline]
1368 pub fn as_cstr_mut(&mut self) -> &CStr {
1369 unsafe {
1370 self.0[SIZE - 1] = 0; // Ensure null-termination
1371 CStr::from_ptr(self.0.as_ptr() as *const c_char)
1372 }
1373 }
1374
1375 /// Appends a string slice to the existing content in the `Bytes` buffer.
1376 ///
1377 /// This method finds the current end of the content (first null byte) and appends
1378 /// the provided string starting from that position. If the buffer is already full
1379 /// or if the appended content would exceed the buffer size, the content is truncated
1380 /// to fit within the `SIZE` limit.
1381 ///
1382 /// # Parameters
1383 ///
1384 /// * `str` - The string slice to append
1385 ///
1386 /// # Examples
1387 ///
1388 /// ```
1389 /// use osal_rs::utils::Bytes;
1390 ///
1391 /// let mut bytes = Bytes::<16>::new_by_str("Hello");
1392 /// bytes.append_str(" World");
1393 /// assert_eq!(bytes.as_str(), "Hello World");
1394 ///
1395 /// // Truncation when exceeding buffer size
1396 /// let mut small_bytes = Bytes::<8>::new_by_str("Hi");
1397 /// small_bytes.append_str(" there friend");
1398 /// assert_eq!(small_bytes.as_str(), "Hi ther");
1399 /// ```
1400 pub fn append_str(&mut self, str: &str) {
1401 let current_len = self.0.iter().position(|&b| b == 0).unwrap_or(SIZE);
1402 let mut i = current_len;
1403 for byte in str.as_bytes() {
1404 if i > SIZE - 1{
1405 break;
1406 }
1407 self.0[i] = *byte;
1408 i += 1;
1409 }
1410 }
1411
1412 /// Appends content from any type implementing `AsSyncStr` to the buffer.
1413 ///
1414 /// This method accepts any type that implements the `AsSyncStr` trait, converts
1415 /// it to a string slice, and appends it to the existing content. If the buffer
1416 /// is already full or if the appended content would exceed the buffer size,
1417 /// the content is truncated to fit within the `SIZE` limit.
1418 ///
1419 /// # Parameters
1420 ///
1421 /// * `c_str` - A reference to any type implementing `AsSyncStr`
1422 ///
1423 /// # Examples
1424 ///
1425 /// ```ignore
1426 /// use osal_rs::utils::Bytes;
1427 ///
1428 /// let mut bytes = Bytes::<16>::new_by_str("Hello");
1429 /// let other_bytes = Bytes::<8>::new_by_str(" World");
1430 /// bytes.append_as_sync_str(&other_bytes);
1431 /// assert_eq!(bytes.as_str(), "Hello World");
1432 /// ```
1433 pub fn append_as_sync_str(&mut self, c_str: & impl AsSyncStr) {
1434 let current_len = self.0.iter().position(|&b| b == 0).unwrap_or(SIZE);
1435 let mut i = current_len;
1436 for byte in c_str.as_str().as_bytes() {
1437 if i > SIZE - 1{
1438 break;
1439 }
1440 self.0[i] = *byte;
1441 i += 1;
1442 }
1443 }
1444
1445 /// Appends raw bytes to the existing content in the `Bytes` buffer.
1446 ///
1447 /// This method finds the current end of the content (first null byte) and appends
1448 /// the provided byte slice starting from that position. If the buffer is already
1449 /// full or if the appended content would exceed the buffer size, the content is
1450 /// truncated to fit within the `SIZE` limit.
1451 ///
1452 /// # Parameters
1453 ///
1454 /// * `bytes` - The byte slice to append
1455 ///
1456 /// # Examples
1457 ///
1458 /// ```
1459 /// use osal_rs::utils::Bytes;
1460 ///
1461 /// let mut bytes = Bytes::<16>::new_by_str("Hello");
1462 /// bytes.append_bytes(b" World");
1463 /// assert_eq!(bytes.as_str(), "Hello World");
1464 ///
1465 /// // Appending arbitrary bytes
1466 /// let mut data = Bytes::<16>::new_by_str("Data: ");
1467 /// data.append_bytes(&[0x41, 0x42, 0x43]);
1468 /// assert_eq!(data.as_str(), "Data: ABC");
1469 /// ```
1470 pub fn append_bytes(&mut self, bytes: &[u8]) {
1471 let current_len = self.0.iter().position(|&b| b == 0).unwrap_or(SIZE);
1472 let mut i = current_len;
1473 for byte in bytes {
1474 if i > SIZE - 1{
1475 break;
1476 }
1477 self.0[i] = *byte;
1478 i += 1;
1479 }
1480 }
1481
1482 /// Appends the content of another `Bytes` instance to this buffer.
1483 ///
1484 /// This method allows appending content from a `Bytes` instance of a different
1485 /// size (specified by the generic parameter `OHTER_SIZE`). The method finds the
1486 /// current end of the content (first null byte) and appends the content from the
1487 /// other `Bytes` instance. If the buffer is already full or if the appended content
1488 /// would exceed the buffer size, the content is truncated to fit within the `SIZE` limit.
1489 ///
1490 /// # Type Parameters
1491 ///
1492 /// * `OTHER_SIZE` - The size of the source `Bytes` buffer (can be different from `SIZE`)
1493 ///
1494 /// # Parameters
1495 ///
1496 /// * `other` - A reference to the `Bytes` instance to append
1497 ///
1498 /// # Examples
1499 ///
1500 /// ```
1501 /// use osal_rs::utils::Bytes;
1502 ///
1503 /// let mut bytes = Bytes::<16>::new_by_str("Hello");
1504 /// let other = Bytes::<8>::new_by_str(" World");
1505 /// bytes.append(&other);
1506 /// assert_eq!(bytes.as_str(), "Hello World");
1507 ///
1508 /// // Appending from a larger buffer
1509 /// let mut small = Bytes::<8>::new_by_str("Hi");
1510 /// let large = Bytes::<32>::new_by_str(" there friend");
1511 /// small.append(&large);
1512 /// assert_eq!(small.as_str(), "Hi ther");
1513 /// ```
1514 pub fn append<const OTHER_SIZE: usize>(&mut self, other: &Bytes<OTHER_SIZE>) {
1515 let current_len = self.0.iter().position(|&b| b == 0).unwrap_or(SIZE);
1516 let mut i = current_len;
1517 for &byte in other.0.iter() {
1518 if i > SIZE - 1{
1519 break;
1520 }
1521 self.0[i] = byte;
1522 i += 1;
1523 }
1524 }
1525
1526 /// Clears all content from the buffer, filling it with zeros.
1527 ///
1528 /// This method resets the entire internal byte array to zeros, effectively
1529 /// clearing any stored data. After calling this method, the buffer will be
1530 /// empty and ready for new content.
1531 ///
1532 /// # Examples
1533 ///
1534 /// ```ignore
1535 /// use osal_rs::utils::Bytes;
1536 ///
1537 /// let mut bytes = Bytes::<16>::new_by_str("Hello");
1538 /// assert!(!bytes.is_empty());
1539 ///
1540 /// bytes.clear();
1541 /// assert!(bytes.is_empty());
1542 /// assert_eq!(bytes.len(), 0);
1543 /// ```
1544 pub fn clear(&mut self) {
1545 for byte in self.0.iter_mut() {
1546 *byte = 0;
1547 }
1548 }
1549
1550 /// Returns the length of the content in the buffer.
1551 ///
1552 /// The length is determined by finding the position of the first null byte (0).
1553 /// If no null byte is found, returns `SIZE`, indicating the buffer is completely
1554 /// filled with non-zero data.
1555 ///
1556 /// # Returns
1557 ///
1558 /// The number of bytes before the first null terminator, or `SIZE` if the
1559 /// buffer is completely filled.
1560 ///
1561 /// # Examples
1562 ///
1563 /// ```ignore
1564 /// use osal_rs::utils::Bytes;
1565 ///
1566 /// let bytes = Bytes::<16>::new_by_str("Hello");
1567 /// assert_eq!(bytes.len(), 5);
1568 ///
1569 /// let empty = Bytes::<16>::new();
1570 /// assert_eq!(empty.len(), 0);
1571 ///
1572 /// // Buffer completely filled (no null terminator)
1573 /// let mut full = Bytes::<4>::new();
1574 /// full[0] = b'A';
1575 /// full[1] = b'B';
1576 /// full[2] = b'C';
1577 /// full[3] = b'D';
1578 /// assert_eq!(full.len(), 4);
1579 /// ```
1580 #[inline]
1581 pub fn len(&self) -> usize {
1582 self.0.iter().position(|&b| b == 0).unwrap_or(SIZE)
1583 }
1584
1585 /// Checks if the buffer is empty.
1586 ///
1587 /// A buffer is considered empty if all bytes are zero. This method searches
1588 /// for the first non-zero byte to determine emptiness.
1589 ///
1590 /// # Returns
1591 ///
1592 /// `true` if all bytes are zero, `false` otherwise.
1593 ///
1594 /// # Examples
1595 ///
1596 /// ```ignore
1597 /// use osal_rs::utils::Bytes;
1598 ///
1599 /// let empty = Bytes::<16>::new();
1600 /// assert!(empty.is_empty());
1601 ///
1602 /// let bytes = Bytes::<16>::new_by_str("Hello");
1603 /// assert!(!bytes.is_empty());
1604 ///
1605 /// let mut cleared = Bytes::<16>::new_by_str("Test");
1606 /// cleared.clear();
1607 /// assert!(cleared.is_empty());
1608 /// ```
1609 #[inline]
1610 pub fn is_empty(&self) -> bool {
1611 self.0.iter().position(|&b| b != 0).is_none()
1612 }
1613
1614 /// Returns the total capacity of the buffer.
1615 ///
1616 /// This is the fixed size of the internal byte array, determined at compile
1617 /// time by the generic `SIZE` parameter. The capacity never changes during
1618 /// the lifetime of the `Bytes` instance.
1619 ///
1620 /// # Returns
1621 ///
1622 /// The total capacity in bytes (`SIZE`).
1623 ///
1624 /// # Examples
1625 ///
1626 /// ```ignore
1627 /// use osal_rs::utils::Bytes;
1628 ///
1629 /// let bytes = Bytes::<32>::new();
1630 /// assert_eq!(bytes.capacity(), 32);
1631 ///
1632 /// let other = Bytes::<128>::new_by_str("Hello");
1633 /// assert_eq!(other.capacity(), 128);
1634 /// ```
1635 #[inline]
1636 pub fn capacity(&self) -> usize {
1637 SIZE
1638 }
1639
1640 /// Replaces all occurrences of a byte pattern with another pattern.
1641 ///
1642 /// This method searches for all occurrences of the `find` byte sequence within
1643 /// the buffer and replaces them with the `replace` byte sequence. The replacement
1644 /// is performed in a single pass, and the method handles cases where the replacement
1645 /// is larger, smaller, or equal in size to the pattern being searched for.
1646 ///
1647 /// # Parameters
1648 ///
1649 /// * `find` - The byte pattern to search for
1650 /// * `replace` - The byte pattern to replace with
1651 ///
1652 /// # Returns
1653 ///
1654 /// * `Ok(())` - If all replacements were successful
1655 /// * `Err(Error::StringConversionError)` - If the replacement would exceed the buffer capacity
1656 ///
1657 /// # Behavior
1658 ///
1659 /// - Empty `find` patterns are ignored (returns `Ok(())` immediately)
1660 /// - Multiple occurrences are replaced in a single pass
1661 /// - Content is properly shifted when replacement size differs from find size
1662 /// - Null terminators and trailing bytes are correctly maintained
1663 /// - Overlapping patterns are not re-matched (avoids infinite loops)
1664 ///
1665 /// # Examples
1666 ///
1667 /// ```ignore
1668 /// use osal_rs::utils::Bytes;
1669 ///
1670 /// // Same length replacement
1671 /// let mut bytes = Bytes::<16>::new_by_str("Hello World");
1672 /// bytes.replace(b"World", b"Rust!").unwrap();
1673 /// assert_eq!(bytes.as_str(), "Hello Rust!");
1674 ///
1675 /// // Shorter replacement
1676 /// let mut bytes2 = Bytes::<16>::new_by_str("aabbcc");
1677 /// bytes2.replace(b"bb", b"X").unwrap();
1678 /// assert_eq!(bytes2.as_str(), "aaXcc");
1679 ///
1680 /// // Longer replacement
1681 /// let mut bytes3 = Bytes::<16>::new_by_str("Hi");
1682 /// bytes3.replace(b"Hi", b"Hello").unwrap();
1683 /// assert_eq!(bytes3.as_str(), "Hello");
1684 ///
1685 /// // Multiple occurrences
1686 /// let mut bytes4 = Bytes::<32>::new_by_str("foo bar foo");
1687 /// bytes4.replace(b"foo", b"baz").unwrap();
1688 /// assert_eq!(bytes4.as_str(), "baz bar baz");
1689 ///
1690 /// // Buffer overflow error
1691 /// let mut small = Bytes::<8>::new_by_str("Hello");
1692 /// assert!(small.replace(b"Hello", b"Hello World").is_err());
1693 /// ```
1694 pub fn replace(&mut self, find: &[u8], replace: &[u8]) -> Result<()> {
1695 if find.is_empty() {
1696 return Ok(());
1697 }
1698
1699 let mut i = 0;
1700 loop {
1701 let current_len = self.len();
1702
1703 // Exit if we've reached the end
1704 if i >= current_len {
1705 break;
1706 }
1707
1708 // Check if pattern starts at position i
1709 if i + find.len() <= current_len && self.0[i..i + find.len()] == *find {
1710 let remaining_len = current_len - (i + find.len());
1711 let new_len = i + replace.len() + remaining_len;
1712
1713 // Check if replacement fits in buffer
1714 if new_len > SIZE {
1715 return Err(Error::StringConversionError);
1716 }
1717
1718 // Shift remaining content if sizes differ
1719 if replace.len() != find.len() {
1720 self.0.copy_within(
1721 i + find.len()..i + find.len() + remaining_len,
1722 i + replace.len()
1723 );
1724 }
1725
1726 // Insert replacement bytes
1727 self.0[i..i + replace.len()].copy_from_slice(replace);
1728
1729 // Update null terminator position
1730 if new_len < SIZE {
1731 self.0[new_len] = 0;
1732 }
1733
1734 // Clear trailing bytes if content shrunk
1735 if new_len < current_len {
1736 for j in (new_len + 1)..=current_len {
1737 if j < SIZE {
1738 self.0[j] = 0;
1739 }
1740 }
1741 }
1742
1743 // Move past the replacement to avoid infinite loops
1744 i += replace.len();
1745 } else {
1746 i += 1;
1747 }
1748 }
1749
1750 Ok(())
1751 }
1752
1753 /// Converts the `Bytes` instance to a byte slice.
1754 ///
1755 /// This method provides a convenient way to access the internal byte array
1756 /// as a slice, which can be useful for C FFI or other operations that
1757 /// require byte slices.
1758 ///
1759 /// # Examples
1760 ///
1761 /// ```ignore
1762 /// use osal_rs::utils::{Bytes, ToBytes};
1763 ///
1764 /// let bytes = Bytes::<8>::new_by_str("example");
1765 /// let byte_slice = bytes.to_bytes();
1766 /// assert_eq!(byte_slice, b"example\0\0");
1767 /// ```
1768 #[inline]
1769 pub fn to_bytes(&self) -> &[u8] {
1770 &self.0
1771 }
1772}
1773
1774/// Converts a byte slice to a hexadecimal string representation.
1775///
1776/// Each byte is converted to its two-character hexadecimal representation
1777/// in lowercase. This function allocates a new `String` on the heap.
1778///
1779/// # Parameters
1780///
1781/// * `bytes` - The byte slice to convert
1782///
1783/// # Returns
1784///
1785/// A `String` containing the hexadecimal representation of the bytes.
1786/// Each byte is represented by exactly 2 hex characters (lowercase).
1787///
1788/// # Memory Allocation
1789///
1790/// This function allocates heap memory. In memory-constrained environments,
1791/// consider using [`bytes_to_hex_into_slice`] instead.
1792///
1793/// # Examples
1794///
1795/// ```ignore
1796/// use osal_rs::utils::bytes_to_hex;
1797///
1798/// let data = &[0x01, 0x23, 0xAB, 0xFF];
1799/// let hex = bytes_to_hex(data);
1800/// assert_eq!(hex, "0123abff");
1801///
1802/// let empty = bytes_to_hex(&[]);
1803/// assert_eq!(empty, "");
1804/// ```
1805#[inline]
1806pub fn bytes_to_hex(bytes: &[u8]) -> String {
1807 bytes.iter()
1808 .map(|b| format!("{:02x}", b))
1809 .collect()
1810}
1811
1812/// Converts a byte slice to hexadecimal representation into a pre-allocated buffer.
1813///
1814/// This is a zero-allocation version of [`bytes_to_hex`] that writes the
1815/// hexadecimal representation directly into a provided output buffer.
1816/// Suitable for embedded systems and real-time applications.
1817///
1818/// # Parameters
1819///
1820/// * `bytes` - The source byte slice to convert
1821/// * `output` - The destination buffer to write hex characters into
1822///
1823/// # Returns
1824///
1825/// The number of bytes written to the output buffer (always `bytes.len() * 2`).
1826///
1827/// # Panics
1828///
1829/// Panics if `output.len() < bytes.len() * 2`. The output buffer must be
1830/// at least twice the size of the input to hold the hex representation.
1831///
1832/// # Examples
1833///
1834/// ```ignore
1835/// use osal_rs::utils::bytes_to_hex_into_slice;
1836///
1837/// let data = &[0x01, 0xAB, 0xFF];
1838/// let mut buffer = [0u8; 6];
1839///
1840/// let written = bytes_to_hex_into_slice(data, &mut buffer);
1841/// assert_eq!(written, 6);
1842/// assert_eq!(&buffer, b"01abff");
1843///
1844/// // Will panic - buffer too small
1845/// // let mut small = [0u8; 4];
1846/// // bytes_to_hex_into_slice(data, &mut small);
1847/// ```
1848pub fn bytes_to_hex_into_slice(bytes: &[u8], output: &mut [u8]) -> usize {
1849 assert!(output.len() >= bytes.len() * 2, "Buffer too small for hex conversion");
1850 let mut i = 0;
1851 for &b in bytes {
1852 let hex = format!("{:02x}", b);
1853 output[i..i+2].copy_from_slice(hex.as_bytes());
1854 i += 2;
1855 }
1856 i
1857}
1858
1859/// Converts a hexadecimal string to a vector of bytes.
1860///
1861/// Parses a string of hexadecimal digits (case-insensitive) and converts
1862/// them to their binary representation. Each pair of hex digits becomes
1863/// one byte in the output.
1864///
1865/// # Parameters
1866///
1867/// * `hex` - A string slice containing hexadecimal digits (0-9, a-f, A-F)
1868///
1869/// # Returns
1870///
1871/// * `Ok(Vec<u8>)` - A vector containing the decoded bytes
1872/// * `Err(Error::StringConversionError)` - If the string has odd length or contains invalid hex digits
1873///
1874/// # Memory Allocation
1875///
1876/// This function allocates a `Vec` on the heap. For no-alloc environments,
1877/// use [`hex_to_bytes_into_slice`] instead.
1878///
1879/// # Examples
1880///
1881/// ```ignore
1882/// use osal_rs::utils::hex_to_bytes;
1883///
1884/// // Lowercase hex
1885/// let bytes = hex_to_bytes("0123abff").unwrap();
1886/// assert_eq!(bytes, vec![0x01, 0x23, 0xAB, 0xFF]);
1887///
1888/// // Uppercase hex
1889/// let bytes2 = hex_to_bytes("ABCD").unwrap();
1890/// assert_eq!(bytes2, vec![0xAB, 0xCD]);
1891///
1892/// // Odd length - error
1893/// assert!(hex_to_bytes("ABC").is_err());
1894///
1895/// // Invalid character - error
1896/// assert!(hex_to_bytes("0G").is_err());
1897/// ```
1898pub fn hex_to_bytes(hex: &str) -> Result<Vec<u8>> {
1899 if hex.len() % 2 != 0 {
1900 return Err(Error::StringConversionError);
1901 }
1902
1903 let bytes_result: Result<Vec<u8>> = (0..hex.len())
1904 .step_by(2)
1905 .map(|i| {
1906 u8::from_str_radix(&hex[i..i + 2], 16)
1907 .map_err(|_| Error::StringConversionError)
1908 })
1909 .collect();
1910
1911 bytes_result
1912}
1913
1914/// Converts a hexadecimal string to bytes into a pre-allocated buffer.
1915///
1916/// This is a zero-allocation version of [`hex_to_bytes`] that writes decoded
1917/// bytes directly into a provided output buffer. Suitable for embedded systems
1918/// and real-time applications where heap allocation is not desired.
1919///
1920/// # Parameters
1921///
1922/// * `hex` - A string slice containing hexadecimal digits (0-9, a-f, A-F)
1923/// * `output` - The destination buffer to write decoded bytes into
1924///
1925/// # Returns
1926///
1927/// * `Ok(usize)` - The number of bytes written to the output buffer (`hex.len() / 2`)
1928/// * `Err(Error::StringConversionError)` - If:
1929/// - The hex string has odd length
1930/// - The output buffer is too small (`output.len() < hex.len() / 2`)
1931/// - The hex string contains invalid characters
1932///
1933/// # Examples
1934///
1935/// ```ignore
1936/// use osal_rs::utils::hex_to_bytes_into_slice;
1937///
1938/// let mut buffer = [0u8; 4];
1939/// let written = hex_to_bytes_into_slice("0123abff", &mut buffer).unwrap();
1940/// assert_eq!(written, 4);
1941/// assert_eq!(buffer, [0x01, 0x23, 0xAB, 0xFF]);
1942///
1943/// // Buffer too small
1944/// let mut small = [0u8; 2];
1945/// assert!(hex_to_bytes_into_slice("0123abff", &mut small).is_err());
1946///
1947/// // Odd length string
1948/// assert!(hex_to_bytes_into_slice("ABC", &mut buffer).is_err());
1949/// ```
1950pub fn hex_to_bytes_into_slice(hex: &str, output: &mut [u8]) -> Result<usize> {
1951 if hex.len() % 2 != 0 || output.len() < hex.len() / 2 {
1952 return Err(Error::StringConversionError);
1953 }
1954
1955 for i in 0..(hex.len() / 2) {
1956 output[i] = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16)
1957 .map_err(|_| Error::StringConversionError)?;
1958 }
1959
1960 Ok(hex.len() / 2)
1961}
1962
1963/// Thread-safe wrapper for `UnsafeCell` usable in `static` contexts.
1964///
1965/// `SyncUnsafeCell<T>` is a thin wrapper around `UnsafeCell<T>` that manually
1966/// implements the `Sync` and `Send` traits, allowing its use in `static` variables.
1967/// This is necessary in Rust 2024+ where `static mut` is no longer allowed.
1968///
1969/// # Safety
1970///
1971/// The manual implementation of `Sync` and `Send` is **unsafe** because the compiler
1972/// cannot verify that concurrent access is safe. It is the programmer's responsibility
1973/// to ensure that:
1974///
1975/// 1. In **single-threaded** environments (e.g., embedded bare-metal), there are no
1976/// synchronization issues since only one thread of execution exists.
1977///
1978/// 2. In **multi-threaded** environments, access to `SyncUnsafeCell` must be
1979/// externally protected via mutexes, critical sections, or other synchronization
1980/// primitives.
1981///
1982/// 3. No **data race** conditions occur during data access.
1983///
1984/// # Typical Usage
1985///
1986/// This structure is designed to replace `static mut` in embedded scenarios
1987/// where global mutability is necessary (e.g., hardware registers, shared buffers).
1988///
1989/// # Examples
1990///
1991/// ```ignore
1992/// use osal_rs::utils::SyncUnsafeCell;
1993///
1994/// // Global mutable variable in Rust 2024+
1995/// static COUNTER: SyncUnsafeCell<u32> = SyncUnsafeCell::new(0);
1996///
1997/// fn increment_counter() {
1998/// unsafe {
1999/// let counter = &mut *COUNTER.get();
2000/// *counter += 1;
2001/// }
2002/// }
2003/// ```
2004///
2005/// # Alternatives
2006///
2007/// For non-embedded code or when real synchronization is needed:
2008/// - Use `Mutex<T>` or `RwLock<T>` for thread-safe protection
2009/// - Use `AtomicUsize`, `AtomicBool`, etc. for simple atomic types
2010pub struct SyncUnsafeCell<T>(UnsafeCell<T>);
2011
2012/// Manual implementation of `Sync` for `SyncUnsafeCell<T>`.
2013///
2014/// # Safety
2015///
2016/// This is **unsafe** because it asserts that `SyncUnsafeCell<T>` can be shared
2017/// between threads without causing data races. The caller must ensure synchronization.
2018unsafe impl<T> Sync for SyncUnsafeCell<T> {}
2019
2020/// Manual implementation of `Send` for `SyncUnsafeCell<T>`.
2021///
2022/// # Safety
2023///
2024/// This is **unsafe** because it asserts that `SyncUnsafeCell<T>` can be transferred
2025/// between threads. The inner type `T` may not be `Send`, so the caller must handle
2026/// memory safety.
2027unsafe impl<T> Send for SyncUnsafeCell<T> {}
2028
2029impl<T> SyncUnsafeCell<T> {
2030 /// Creates a new instance of `SyncUnsafeCell<T>`.
2031 ///
2032 /// This is a `const` function, allowing initialization in static and
2033 /// constant contexts.
2034 ///
2035 /// # Parameters
2036 ///
2037 /// * `value` - The initial value to wrap
2038 ///
2039 /// # Examples
2040 ///
2041 /// ```ignore
2042 /// use osal_rs::utils::SyncUnsafeCell;
2043 ///
2044 /// static CONFIG: SyncUnsafeCell<u32> = SyncUnsafeCell::new(42);
2045 /// ```
2046 #[inline]
2047 pub const fn new(value: T) -> Self {
2048 Self(UnsafeCell::new(value))
2049 }
2050
2051 /// Gets a raw mutable pointer to the contained value.
2052 ///
2053 /// # Safety
2054 ///
2055 /// This function is **unsafe** because:
2056 /// - It returns a raw pointer that bypasses the borrow checker
2057 /// - The caller must ensure there are no mutable aliases
2058 /// - Dereferencing the pointer without synchronization can cause data races
2059 ///
2060 /// # Returns
2061 ///
2062 /// A raw mutable pointer `*mut T` to the inner value.
2063 ///
2064 /// # Examples
2065 ///
2066 /// ```ignore
2067 /// use osal_rs::utils::SyncUnsafeCell;
2068 ///
2069 /// static VALUE: SyncUnsafeCell<i32> = SyncUnsafeCell::new(0);
2070 ///
2071 /// unsafe {
2072 /// let ptr = VALUE.get();
2073 /// *ptr = 42;
2074 /// }
2075 /// ```
2076 #[inline]
2077 pub unsafe fn get(&self) -> *mut T {
2078 self.0.get()
2079 }
2080}