osal-rs 0.4.5

Operating System Abstraction Layer for Rust with support for FreeRTOS and POSIX
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
/***************************************************************************
 *
 * osal-rs
 * Copyright (C) 2026 Antonio Salsi <passy.linux@zresa.it>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <https://www.gnu.org/licenses/>.
 *
 ***************************************************************************/

//! Queue-based inter-thread communication for FreeRTOS.
//!
//! This module provides FIFO queue primitives for safe message passing between threads
//! and interrupt service routines. Supports both byte-based and typed queues.

use core::ffi::c_void;
use core::fmt::{Debug, Display};
use core::marker::PhantomData;
use core::ops::Deref;

use alloc::vec::Vec;

use super::ffi::{QueueHandle, pdFALSE, vQueueDelete, xQueueGenericCreate, xQueueReceive, xQueueReceiveFromISR};
use super::types::{BaseType, UBaseType, TickType};
use super::system::System;
use crate::traits::{ToTick, QueueFn, SystemFn, QueueStreamedFn, BytesHasLen};
#[cfg(not(feature = "serde"))]
use crate::traits::{Serialize, Deserialize};

#[cfg(feature = "serde")]
use osal_rs_serde::{Serialize, Deserialize, to_bytes};

pub trait StructSerde : Serialize + BytesHasLen + Deserialize {}

use crate::utils::{Result, Error};


/// A FIFO queue for byte-based message passing.
///
/// Provides a thread-safe queue implementation for sending and receiving
/// raw byte slices between threads. Supports both blocking and ISR-safe operations.
///
/// # Examples
///
/// ## Basic queue usage
///
/// ```ignore
/// use osal_rs::os::{Queue, QueueFn};
/// use core::time::Duration;
/// 
/// // Create a queue with 10 slots, each 32 bytes
/// let queue = Queue::new(10, 32).unwrap();
/// 
/// // Send data
/// let data = [1u8, 2, 3, 4];
/// queue.post_with_to_tick(&data, Duration::from_millis(100)).unwrap();
/// 
/// // Receive data
/// let mut buffer = [0u8; 4];
/// queue.fetch_with_to_tick(&mut buffer, Duration::from_millis(100)).unwrap();
/// assert_eq!(buffer, [1, 2, 3, 4]);
/// ```
///
/// ## Producer-consumer pattern
///
/// ```ignore
/// use osal_rs::os::{Queue, QueueFn, Thread};
/// use alloc::sync::Arc;
/// use core::time::Duration;
/// 
/// let queue = Arc::new(Queue::new(5, 4).unwrap());
/// let queue_clone = queue.clone();
/// 
/// // Consumer thread
/// let consumer = Thread::new("consumer", 2048, 5, move || {
///     let mut buffer = [0u8; 4];
///     loop {
///         if queue_clone.fetch(&mut buffer, 1000).is_ok() {
///             println!("Received: {:?}", buffer);
///         }
///     }
/// }).unwrap();
/// 
/// consumer.start().unwrap();
/// 
/// // Producer
/// let data = [0xAA, 0xBB, 0xCC, 0xDD];
/// queue.post(&data, 1000).unwrap();
/// ```
pub struct Queue (QueueHandle);

unsafe impl Send for Queue {}
unsafe impl Sync for Queue {}

impl Queue {
    /// Creates a new queue.
    ///
    /// # Parameters
    ///
    /// * `size` - Maximum number of messages the queue can hold
    /// * `message_size` - Size in bytes of each message
    ///
    /// # Returns
    ///
    /// * `Ok(Self)` - Successfully created queue
    /// * `Err(Error)` - Creation failed (insufficient memory, etc.)
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use osal_rs::os::{Queue, QueueFn};
    /// 
    /// // Queue for 5 messages of 16 bytes each
    /// let queue = Queue::new(5, 16).unwrap();
    /// ```
    pub fn new (size: UBaseType, message_size: UBaseType) -> Result<Self> {
        const QUEUE_TYPE_BASE: u8 = 0; // queueQUEUE_TYPE_BASE
        let handle = unsafe { xQueueGenericCreate(size, message_size, QUEUE_TYPE_BASE) };
        if handle.is_null() {
            Err(Error::OutOfMemory)
        } else {
            Ok(Self (handle))
        }
    }

    /// Receives data from the queue with a convertible timeout.
    /// 
    /// This is a convenience method that accepts any type implementing `ToTick`
    /// (like `Duration`) and converts it to ticks before calling `fetch()`.
    /// 
    /// # Arguments
    /// 
    /// * `buffer` - Mutable slice to receive data into
    /// * `time` - Timeout value (e.g., `Duration::from_millis(100)`)
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Data successfully received
    /// * `Err(Error::Timeout)` - No data available within timeout
    /// 
    /// # Examples
    /// 
    /// ```ignore
    /// use osal_rs::os::{Queue, QueueFn};
    /// use core::time::Duration;
    /// 
    /// let queue = Queue::new(5, 16).unwrap();
    /// let mut buffer = [0u8; 16];
    /// queue.fetch_with_to_tick(&mut buffer, Duration::from_millis(100))?;
    /// ```
    #[inline]
    pub fn fetch_with_to_tick(&self, buffer: &mut [u8], time: impl ToTick) -> Result<()> {
        self.fetch(buffer, time.to_ticks())
    }

    /// Sends data to the queue with a convertible timeout.
    /// 
    /// This is a convenience method that accepts any type implementing `ToTick`
    /// (like `Duration`) and converts it to ticks before calling `post()`.
    /// 
    /// # Arguments
    /// 
    /// * `item` - Slice of data to send
    /// * `time` - Timeout value (e.g., `Duration::from_millis(100)`)
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Data successfully sent
    /// * `Err(Error::Timeout)` - Queue full, could not send within timeout
    /// 
    /// # Examples
    /// 
    /// ```ignore
    /// use osal_rs::os::{Queue, QueueFn};
    /// use core::time::Duration;
    /// 
    /// let queue = Queue::new(5, 16).unwrap();
    /// let data = [1u8, 2, 3, 4];
    /// queue.post_with_to_tick(&data, Duration::from_millis(100))?;
    /// ```
    #[inline]
    pub fn post_with_to_tick(&self, item: &[u8], time: impl ToTick) -> Result<()> {
        self.post(item, time.to_ticks())
    }
}

impl QueueFn for Queue {

    /// Receives data from the queue, blocking until data is available or timeout.
    /// 
    /// This function blocks the calling thread until data is available or the
    /// specified timeout expires.
    /// 
    /// # Arguments
    /// 
    /// * `buffer` - Mutable byte slice to receive data into
    /// * `time` - Timeout in system ticks (0 = no wait, MAX = wait forever)
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Data successfully received into buffer
    /// * `Err(Error::Timeout)` - No data available within timeout period
    /// 
    /// # Examples
    /// 
    /// ```ignore
    /// use osal_rs::os::{Queue, QueueFn};
    /// 
    /// let queue = Queue::new(5, 16).unwrap();
    /// let mut buffer = [0u8; 16];
    /// 
    /// // Wait up to 1000 ticks for data
    /// match queue.fetch(&mut buffer, 1000) {
    ///     Ok(()) => println!("Received data: {:?}", buffer),
    ///     Err(_) => println!("Timeout"),
    /// }
    /// ```
    fn fetch(&self, buffer: &mut [u8], time: TickType) -> Result<()> {
        let ret = unsafe {
            xQueueReceive(
                self.0,
                buffer.as_mut_ptr() as *mut c_void,
                time,
            )
        };
        if ret == 0 {
            Err(Error::Timeout)
        } else {
            Ok(())
        }
    }

    /// Receives data from the queue in an interrupt service routine (ISR).
    /// 
    /// This is the ISR-safe version of `fetch()`. It does not block and will
    /// trigger a context switch if a higher priority task is woken.
    /// 
    /// # Arguments
    /// 
    /// * `buffer` - Mutable byte slice to receive data into
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Data successfully received
    /// * `Err(Error::Timeout)` - Queue is empty
    /// 
    /// # Safety
    /// 
    /// Must only be called from ISR context.
    /// 
    /// # Examples
    /// 
    /// ```ignore
    /// // In interrupt handler
    /// use osal_rs::os::{Queue, QueueFn};
    /// 
    /// fn irq_handler(queue: &Queue) {
    ///     let mut buffer = [0u8; 16];
    ///     if queue.fetch_from_isr(&mut buffer).is_ok() {
    ///         // Process received data
    ///     }
    /// }
    /// ```
    fn fetch_from_isr(&self, buffer: &mut [u8]) -> Result<()> {

        let mut task_woken_by_receive: BaseType = pdFALSE;

        let ret = unsafe {
            xQueueReceiveFromISR(
                self.0,
                buffer.as_mut_ptr() as *mut c_void,
                &mut task_woken_by_receive
            )
        };
        if ret == 0 {
            Err(Error::Timeout)
        } else {

            System::yield_from_isr(task_woken_by_receive);
            
            Ok(())
        }
    }

    /// Sends data to the back of the queue, blocking until space is available.
    /// 
    /// This function blocks the calling thread until space becomes available
    /// or the timeout expires.
    /// 
    /// # Arguments
    /// 
    /// * `item` - Byte slice to send
    /// * `time` - Timeout in system ticks (0 = no wait, MAX = wait forever)
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Data successfully sent
    /// * `Err(Error::Timeout)` - Queue full, could not send within timeout
    /// 
    /// # Examples
    /// 
    /// ```ignore
    /// use osal_rs::os::{Queue, QueueFn};
    /// 
    /// let queue = Queue::new(5, 16).unwrap();
    /// let data = [0xAA, 0xBB, 0xCC, 0xDD];
    /// 
    /// // Wait up to 1000 ticks to send
    /// queue.post(&data, 1000)?;
    /// ```
    fn post(&self, item: &[u8], time: TickType) -> Result<()> {
        let ret = xQueueSendToBack!(
                            self.0,
                            item.as_ptr() as *const c_void,
                            time
                        );
        
        if ret == 0 {
            Err(Error::Timeout)
        } else {
            Ok(())
        }
    }

    /// Sends data to the queue from an interrupt service routine (ISR).
    /// 
    /// This is the ISR-safe version of `post()`. It does not block and will
    /// trigger a context switch if a higher priority task is woken.
    /// 
    /// # Arguments
    /// 
    /// * `item` - Byte slice to send
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Data successfully sent
    /// * `Err(Error::Timeout)` - Queue is full
    /// 
    /// # Safety
    /// 
    /// Must only be called from ISR context.
    /// 
    /// # Examples
    /// 
    /// ```ignore
    /// // In interrupt handler
    /// use osal_rs::os::{Queue, QueueFn};
    /// 
    /// fn irq_handler(queue: &Queue) {
    ///     let data = [0x01, 0x02, 0x03];
    ///     queue.post_from_isr(&data).ok();
    /// }
    /// ```
    fn post_from_isr(&self, item: &[u8]) -> Result<()> {

        let mut task_woken_by_receive: BaseType = pdFALSE;

        let ret = xQueueSendToBackFromISR!(
                            self.0,
                            item.as_ptr() as *const c_void,
                            &mut task_woken_by_receive
                        );
        
        if ret == 0 {
            Err(Error::Timeout)
        } else {
            System::yield_from_isr(task_woken_by_receive);

            Ok(())
        }
    }

    /// Deletes the queue and frees its resources.
    /// 
    /// This function destroys the queue and releases any memory allocated for it.
    /// After calling this, the queue should not be used. The handle is set to null.
    /// 
    /// # Safety
    /// 
    /// Ensure no threads are waiting on this queue before deleting it.
    /// 
    /// # Examples
    /// 
    /// ```ignore
    /// use osal_rs::os::{Queue, QueueFn};
    /// 
    /// let mut queue = Queue::new(5, 16).unwrap();
    /// // Use the queue...
    /// queue.delete();
    /// ```
    fn delete(&mut self) {
        unsafe {
            vQueueDelete(self.0);
            self.0 = core::ptr::null_mut();
        }
    }
}

/// Automatically deletes the queue when it goes out of scope.
/// 
/// This ensures proper cleanup of FreeRTOS resources.
impl Drop for Queue {
    fn drop(&mut self) {
        if self.0.is_null() {
            return;
        }
        self.delete();
    }
}

/// Allows dereferencing to the underlying FreeRTOS queue handle.
impl Deref for Queue {
    type Target = QueueHandle;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Formats the queue for debugging purposes.
impl Debug for Queue {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Queue")
            .field("handle", &self.0)
            .finish()
    }
}

/// Formats the queue for display purposes.
impl Display for Queue {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Queue {{ handle: {:?} }}", self.0)
    }
}

/// A type-safe FIFO queue for message passing.
///
/// Unlike [`Queue`], which works with raw byte slices, `QueueStreamed` provides
/// a type-safe interface for sending and receiving structured data. The type must
/// implement serialization traits.
///
/// # Type Parameters
///
/// * `T` - The message type. Must implement `ToBytes`, `BytesHasLen`, and `FromBytes`
///
/// # Examples
///
/// ## Basic typed queue usage
///
/// ```ignore
/// use osal_rs::os::{QueueStreamed, QueueStreamedFn};
/// use core::time::Duration;
/// 
/// #[derive(Debug, Clone, Copy)]
/// struct Message {
///     id: u32,
///     value: i16,
/// }
/// 
/// // Assuming Message implements the required traits
/// let queue: QueueStreamed<Message> = QueueStreamed::new(10, size_of::<Message>()).unwrap();
/// 
/// // Send a message
/// let msg = Message { id: 1, value: 42 };
/// queue.post_with_to_tick(&msg, Duration::from_millis(100)).unwrap();
/// 
/// // Receive a message
/// let mut received = Message { id: 0, value: 0 };
/// queue.fetch_with_to_tick(&mut received, Duration::from_millis(100)).unwrap();
/// assert_eq!(received.id, 1);
/// assert_eq!(received.value, 42);
/// ```
///
/// ## Command queue pattern
///
/// ```ignore
/// use osal_rs::os::{QueueStreamed, Thread};
/// use alloc::sync::Arc;
/// 
/// enum Command {
///     Start,
///     Stop,
///     SetValue(u32),
/// }
/// 
/// let cmd_queue = Arc::new(QueueStreamed::<Command>::new(10, 8).unwrap());
/// let queue_clone = cmd_queue.clone();
/// 
/// let handler = Thread::new("handler", 2048, 5, move || {
///     loop {
///         let mut cmd = Command::Stop;
///         if queue_clone.fetch(&mut cmd, 1000).is_ok() {
///             match cmd {
///                 Command::Start => { /* start operation */ },
///                 Command::Stop => { /* stop operation */ },
///                 Command::SetValue(val) => { /* set value */ },
///             }
///         }
///     }
/// }).unwrap();
/// ```
pub struct QueueStreamed<T: StructSerde> (Queue, PhantomData<T>);

unsafe impl<T: StructSerde> Send for QueueStreamed<T> {}
unsafe impl<T: StructSerde> Sync for QueueStreamed<T> {}

impl<T> QueueStreamed<T> 
where 
    T: StructSerde {
    /// Creates a new type-safe queue.
    ///
    /// # Parameters
    ///
    /// * `size` - Maximum number of messages
    /// * `message_size` - Size of each message (typically `size_of::<T>()`)
    ///
    /// # Returns
    ///
    /// * `Ok(Self)` - Successfully created queue
    /// * `Err(Error)` - Creation failed
    #[inline]
    pub fn new (size: UBaseType, message_size: UBaseType) -> Result<Self> {
        Ok(Self (Queue::new(size, message_size)?, PhantomData))
    }

    /// Receives a typed message with a convertible timeout.
    /// 
    /// This is a convenience method that accepts any type implementing `ToTick`.
    /// 
    /// # Arguments
    /// 
    /// * `buffer` - Mutable reference to receive the message into
    /// * `time` - Timeout value (e.g., `Duration::from_millis(100)`)
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Message successfully received and deserialized
    /// * `Err(Error)` - Timeout or deserialization error
    /// 
    /// # Examples
    /// 
    /// ```ignore
    /// use osal_rs::os::QueueStreamed;
    /// use core::time::Duration;
    /// 
    /// let queue: QueueStreamed<MyMessage> = QueueStreamed::new(5, size_of::<MyMessage>()).unwrap();
    /// let mut msg = MyMessage::default();
    /// queue.fetch_with_to_tick(&mut msg, Duration::from_millis(100))?;
    /// ```
    #[inline]
    fn fetch_with_to_tick(&self, buffer: &mut T, time: impl ToTick) -> Result<()> {
        self.fetch(buffer, time.to_ticks())
    }

    /// Sends a typed message with a convertible timeout.
    /// 
    /// This is a convenience method that accepts any type implementing `ToTick`.
    /// 
    /// # Arguments
    /// 
    /// * `item` - Reference to the message to send
    /// * `time` - Timeout value (e.g., `Duration::from_millis(100)`)
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Message successfully serialized and sent
    /// * `Err(Error)` - Timeout or serialization error
    /// 
    /// # Examples
    /// 
    /// ```ignore
    /// use osal_rs::os::QueueStreamed;
    /// use core::time::Duration;
    /// 
    /// let queue: QueueStreamed<MyMessage> = QueueStreamed::new(5, size_of::<MyMessage>()).unwrap();
    /// let msg = MyMessage { id: 1, value: 42 };
    /// queue.post_with_to_tick(&msg, Duration::from_millis(100))?;
    /// ```
    #[inline]
    fn post_with_to_tick(&self, item: &T, time: impl ToTick) -> Result<()> {
        self.post(item, time.to_ticks())
    }
}

#[cfg(not(feature = "serde"))]
impl<T> QueueStreamedFn<T> for QueueStreamed<T> 
where 
    T: StructSerde {

    /// Receives a typed message from the queue (without serde feature).
    /// 
    /// Deserializes the message from bytes using the custom serialization traits.
    /// 
    /// # Arguments
    /// 
    /// * `buffer` - Mutable reference to receive the deserialized message
    /// * `time` - Timeout in system ticks
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Message successfully received and deserialized
    /// * `Err(Error::Timeout)` - Queue empty or timeout
    /// * `Err(Error)` - Deserialization error
    fn fetch(&self, buffer: &mut T, time: TickType) -> Result<()> {
        let mut buf_bytes = Vec::with_capacity(buffer.len());         

        if let Ok(()) = self.0.fetch(&mut buf_bytes, time) {
            *buffer = T::from_bytes(&buf_bytes)?;
            Ok(())
        } else {
            Err(Error::Timeout)
        }
    }

    /// Receives a typed message from ISR context (without serde feature).
    /// 
    /// ISR-safe version that does not block. Deserializes the message from bytes.
    /// 
    /// # Arguments
    /// 
    /// * `buffer` - Mutable reference to receive the deserialized message
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Message successfully received and deserialized
    /// * `Err(Error::Timeout)` - Queue is empty
    /// * `Err(Error)` - Deserialization error
    /// 
    /// # Safety
    /// 
    /// Must only be called from ISR context.
    fn fetch_from_isr(&self, buffer: &mut T) -> Result<()> {
        let mut buf_bytes = Vec::with_capacity(buffer.len());      

        if let Ok(()) = self.0.fetch_from_isr(&mut buf_bytes) {
            *buffer = T::from_bytes(&buf_bytes)?;
            Ok(())
        } else {
            Err(Error::Timeout)
        }
    }

    /// Sends a typed message to the queue (without serde feature).
    /// 
    /// Serializes the message to bytes using the custom serialization traits.
    /// 
    /// # Arguments
    /// 
    /// * `item` - Reference to the message to send
    /// * `time` - Timeout in system ticks
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Message successfully serialized and sent
    /// * `Err(Error::Timeout)` - Queue full
    /// * `Err(Error)` - Serialization error
    #[inline]
    fn post(&self, item: &T, time: TickType) -> Result<()> {
        self.0.post(&item.to_bytes(), time)
    }

    /// Sends a typed message from ISR context (without serde feature).
    /// 
    /// ISR-safe version that does not block. Serializes the message to bytes.
    /// 
    /// # Arguments
    /// 
    /// * `item` - Reference to the message to send
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Message successfully serialized and sent
    /// * `Err(Error::Timeout)` - Queue is full
    /// * `Err(Error)` - Serialization error
    /// 
    /// # Safety
    /// 
    /// Must only be called from ISR context.
    #[inline]
    fn post_from_isr(&self, item: &T) -> Result<()> {
        self.0.post_from_isr(&item.to_bytes())
    }

    /// Deletes the typed queue.
    /// 
    /// Delegates to the underlying byte queue's delete method.
    #[inline]
    fn delete(&mut self) {
        self.0.delete()
    }
}

#[cfg(feature = "serde")]
impl<T> QueueStreamedFn<T> for QueueStreamed<T> 
where 
    T: StructSerde {

    /// Receives a typed message from the queue (with serde feature).
    /// 
    /// Deserializes the message from bytes using the serde framework.
    /// 
    /// # Arguments
    /// 
    /// * `buffer` - Mutable reference to receive the deserialized message
    /// * `time` - Timeout in system ticks
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Message successfully received and deserialized
    /// * `Err(Error::Timeout)` - Queue empty or timeout
    /// * `Err(Error::Unhandled)` - Deserialization error
    fn fetch(&self, buffer: &mut T, time: TickType) -> Result<()> {
        let mut buf_bytes = Vec::with_capacity(buffer.len());     

        if let Ok(()) = self.0.fetch(&mut buf_bytes, time) {
            
            to_bytes(buffer, &mut buf_bytes).map_err(|_| Error::Unhandled("Deserializiation error"))?;

            Ok(())
        } else {
            Err(Error::Timeout)
        }
    }

    /// Receives a typed message from ISR context (with serde feature).
    /// 
    /// ISR-safe version that does not block. Deserializes using serde.
    /// 
    /// # Arguments
    /// 
    /// * `buffer` - Mutable reference to receive the deserialized message
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Message successfully received and deserialized
    /// * `Err(Error::Timeout)` - Queue is empty
    /// * `Err(Error::Unhandled)` - Deserialization error
    /// 
    /// # Safety
    /// 
    /// Must only be called from ISR context.
    fn fetch_from_isr(&self, buffer: &mut T) -> Result<()> {
        let mut buf_bytes = Vec::with_capacity(buffer.len());       

        if let Ok(()) = self.0.fetch_from_isr(&mut buf_bytes) {
            to_bytes(buffer, &mut buf_bytes).map_err(|_| Error::Unhandled("Deserializiation error"))?;
            Ok(())
        } else {
            Err(Error::Timeout)
        }
    }

    /// Sends a typed message to the queue (with serde feature).
    /// 
    /// Serializes the message to bytes using the serde framework.
    /// 
    /// # Arguments
    /// 
    /// * `item` - Reference to the message to send
    /// * `time` - Timeout in system ticks
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Message successfully serialized and sent
    /// * `Err(Error::Timeout)` - Queue full
    /// * `Err(Error::Unhandled)` - Serialization error
    fn post(&self, item: &T, time: TickType) -> Result<()> {


        let mut buf_bytes = Vec::with_capacity(item.len()); 

        to_bytes(item, &mut buf_bytes).map_err(|_| Error::Unhandled("Deserializiation error"))?;

        self.0.post(&buf_bytes, time)
    }

    /// Sends a typed message from ISR context (with serde feature).
    /// 
    /// ISR-safe version that does not block. Serializes using serde.
    /// 
    /// # Arguments
    /// 
    /// * `item` - Reference to the message to send
    /// 
    /// # Returns
    /// 
    /// * `Ok(())` - Message successfully serialized and sent
    /// * `Err(Error::Timeout)` - Queue is full
    /// * `Err(Error::Unhandled)` - Serialization error
    /// 
    /// # Safety
    /// 
    /// Must only be called from ISR context.
    fn post_from_isr(&self, item: &T) -> Result<()> {

        let mut buf_bytes = Vec::with_capacity(item.len()); 

        to_bytes(item, &mut buf_bytes).map_err(|_| Error::Unhandled("Deserializiation error"))?;

        self.0.post_from_isr(&buf_bytes)
    }

    /// Deletes the typed queue (serde version).
    /// 
    /// Delegates to the underlying byte queue's delete method.
    #[inline]
    fn delete(&mut self) {
        self.0.delete()
    }
}

/// Allows dereferencing to the underlying FreeRTOS queue handle.
impl<T> Deref for QueueStreamed<T> 
where 
    T: StructSerde {
    type Target = QueueHandle;

    fn deref(&self) -> &Self::Target {
        &self.0.0
    }   
}

/// Formats the typed queue for debugging purposes.
impl<T> Debug for QueueStreamed<T> 
where 
    T: StructSerde {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("QueueStreamed")
            .field("handle", &self.0.0)
            .finish()
    }
}

/// Formats the typed queue for display purposes.
impl<T> Display for QueueStreamed<T> 
where 
    T: StructSerde {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "QueueStreamed {{ handle: {:?} }}", self.0.0)
    }
}