Skip to content

Commit 4850c4d

Browse files
committed
zephyr: sys: queue: Add Queue::new()
Add support for dynamically allocate sys::Queues. Signed-off-by: David Brown <[email protected]>
1 parent 56f1d31 commit 4850c4d

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

zephyr/src/sys/queue.rs

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
//! implementation of `zephyr::sys::channel`, which can be used without needing unsafe.
66
77
use core::ffi::c_void;
8+
use core::fmt;
9+
use core::mem;
810

911
use zephyr_sys::{
1012
k_queue,
@@ -13,13 +15,13 @@ use zephyr_sys::{
1315
k_queue_get,
1416
};
1517

18+
use crate::error::Result;
1619
use crate::sys::K_FOREVER;
17-
use crate::object::{StaticKernelObject, Wrapped};
20+
use crate::object::{Fixed, StaticKernelObject, Wrapped};
1821

1922
/// A wrapper around a Zephyr `k_queue` object.
20-
#[derive(Clone, Debug)]
2123
pub struct Queue {
22-
item: *mut k_queue,
24+
item: Fixed<k_queue>,
2325
}
2426

2527
unsafe impl Sync for StaticKernelObject<k_queue> { }
@@ -28,6 +30,21 @@ unsafe impl Sync for Queue { }
2830
unsafe impl Send for Queue { }
2931

3032
impl Queue {
33+
/// Create a new Queue, dynamically allocated.
34+
///
35+
/// This Queue can only be used from system threads.
36+
///
37+
/// **Note**: When a Queue is dropped, any messages that have been added to the queue will be
38+
/// leaked.
39+
#[cfg(CONFIG_RUST_ALLOC)]
40+
pub fn new() -> Result<Queue> {
41+
let item: Fixed<k_queue> = Fixed::new(unsafe { mem::zeroed() });
42+
unsafe {
43+
k_queue_init(item.get());
44+
}
45+
Ok(Queue { item })
46+
}
47+
3148
/// Append an element to the end of a queue.
3249
///
3350
/// This adds an element to the given [`Queue`]. Zephyr requires the
@@ -37,14 +54,14 @@ impl Queue {
3754
///
3855
/// [`Message`]: crate::sync::channel::Message
3956
pub unsafe fn send(&self, data: *mut c_void) {
40-
k_queue_append(self.item, data)
57+
k_queue_append(self.item.get(), data)
4158
}
4259

4360
/// Get an element from a queue.
4461
///
4562
/// This routine removes the first data item from the [`Queue`].
4663
pub unsafe fn recv(&self) -> *mut c_void {
47-
k_queue_get(self.item, K_FOREVER)
64+
k_queue_get(self.item.get(), K_FOREVER)
4865
}
4966
}
5067

@@ -59,7 +76,7 @@ impl Wrapped for StaticKernelObject<k_queue> {
5976
k_queue_init(ptr);
6077
}
6178
Queue {
62-
item: ptr,
79+
item: Fixed::Static(ptr),
6380
}
6481
}
6582
}
@@ -77,3 +94,9 @@ impl Wrapped for StaticKernelObject<k_queue> {
7794
/// my_queue.send(...);
7895
/// ```
7996
pub type StaticQueue = StaticKernelObject<k_queue>;
97+
98+
impl fmt::Debug for Queue {
99+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100+
write!(f, "sys::Queue {:?}", self.item.get())
101+
}
102+
}

0 commit comments

Comments
 (0)