diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3f12beb7..ca372dd4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -68,6 +68,18 @@ jobs: rm renode_${RENODE_VERSION}_amd64.deb pip3 install -r /opt/renode/tests/requirements.txt --no-cache-dir + - name: Check formatting + working-directory: apptest + shell: bash + run: | + for name in $(find . -name Cargo.toml); do + name=$(dirname $name) + echo "Checking formatting of $name" + cd $name + cargo fmt --check + cd - > /dev/null + done + - name: Build firmware working-directory: apptest shell: bash diff --git a/docgen/src/lib.rs b/docgen/src/lib.rs index b29be52b..c2ad48c8 100644 --- a/docgen/src/lib.rs +++ b/docgen/src/lib.rs @@ -11,6 +11,5 @@ extern crate zephyr; #[no_mangle] extern "C" fn rust_main() { - printkln!("Hello world from Rust on {}", - zephyr::kconfig::CONFIG_BOARD); + printkln!("Hello world from Rust on {}", zephyr::kconfig::CONFIG_BOARD); } diff --git a/samples/blinky/src/lib.rs b/samples/blinky/src/lib.rs index 5a22f03a..f8c5536f 100644 --- a/samples/blinky/src/lib.rs +++ b/samples/blinky/src/lib.rs @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 #![no_std] - // Sigh. The check config system requires that the compiler be told what possible config values // there might be. This is completely impossible with both Kconfig and the DT configs, since the // whole point is that we likely need to check for configs that aren't otherwise present in the @@ -12,11 +11,13 @@ use log::warn; use zephyr::raw::GPIO_OUTPUT_ACTIVE; -use zephyr::time::{ Duration, sleep }; +use zephyr::time::{sleep, Duration}; #[no_mangle] extern "C" fn rust_main() { - unsafe { zephyr::set_logger().unwrap(); } + unsafe { + zephyr::set_logger().unwrap(); + } warn!("Starting blinky"); @@ -32,14 +33,17 @@ fn do_blink() { if !led0.is_ready() { warn!("LED is not ready"); - loop { - } + loop {} } - unsafe { led0.configure(&mut gpio_token, GPIO_OUTPUT_ACTIVE); } + unsafe { + led0.configure(&mut gpio_token, GPIO_OUTPUT_ACTIVE); + } let duration = Duration::millis_at_least(500); loop { - unsafe { led0.toggle_pin(&mut gpio_token); } + unsafe { + led0.toggle_pin(&mut gpio_token); + } sleep(duration); } } @@ -47,6 +51,5 @@ fn do_blink() { #[cfg(not(dt = "aliases::led0"))] fn do_blink() { warn!("No leds configured"); - loop { - } + loop {} } diff --git a/samples/hello_world/src/lib.rs b/samples/hello_world/src/lib.rs index 819873f4..ce2a33e6 100644 --- a/samples/hello_world/src/lib.rs +++ b/samples/hello_world/src/lib.rs @@ -7,7 +7,9 @@ use log::info; #[no_mangle] extern "C" fn rust_main() { - unsafe { zephyr::set_logger().unwrap(); } + unsafe { + zephyr::set_logger().unwrap(); + } info!("Hello world from Rust on {}", zephyr::kconfig::CONFIG_BOARD); } diff --git a/samples/philosophers/src/channel.rs b/samples/philosophers/src/channel.rs index 3aef607a..82781201 100644 --- a/samples/philosophers/src/channel.rs +++ b/samples/philosophers/src/channel.rs @@ -8,16 +8,13 @@ extern crate alloc; -use alloc::vec::Vec; use alloc::boxed::Box; +use alloc::vec::Vec; use zephyr::sync::channel::{self, Receiver, Sender}; -use zephyr::{ - kobj_define, - sync::Arc, -}; +use zephyr::{kobj_define, sync::Arc}; -use crate::{NUM_PHIL, ForkSync}; +use crate::{ForkSync, NUM_PHIL}; /// An implementation of ForkSync that uses a server commnicated with channels to perform the /// synchronization. @@ -97,10 +94,7 @@ impl ChannelFork { } impl ChannelSync { - pub fn new( - command: Sender, - reply: (Sender<()>, Receiver<()>)) -> ChannelSync - { + pub fn new(command: Sender, reply: (Sender<()>, Receiver<()>)) -> ChannelSync { ChannelSync { command, reply_send: reply.0, @@ -118,23 +112,20 @@ pub fn get_channel_syncer() -> Vec> { if cfg!(CONFIG_USE_BOUNDED_CHANNELS) { // Use only one message, so that send will block, to ensure that works. (cq_send, cq_recv) = channel::bounded(1); - reply_queues = [(); NUM_PHIL].each_ref().map(|()| { - channel::bounded(1) - }); + reply_queues = [(); NUM_PHIL].each_ref().map(|()| channel::bounded(1)); } else { (cq_send, cq_recv) = channel::unbounded(); - reply_queues = [(); NUM_PHIL].each_ref().map(|()| { - channel::unbounded() - }); + reply_queues = [(); NUM_PHIL].each_ref().map(|()| channel::unbounded()); } let syncer = reply_queues.into_iter().map(|rqueue| { - let item = Box::new(ChannelSync::new(cq_send.clone(), rqueue)) - as Box; + let item = Box::new(ChannelSync::new(cq_send.clone(), rqueue)) as Box; Arc::from(item) }); - let channel_child = CHANNEL_THREAD.init_once(CHANNEL_STACK.init_once(()).unwrap()).unwrap(); + let channel_child = CHANNEL_THREAD + .init_once(CHANNEL_STACK.init_once(()).unwrap()) + .unwrap(); channel_child.spawn(move || { channel_thread(cq_recv); }); @@ -162,7 +153,9 @@ fn channel_thread(cq_recv: Receiver) { impl ForkSync for ChannelSync { fn take(&self, index: usize) { - self.command.send(Command::Acquire(index, self.reply_send.clone())).unwrap(); + self.command + .send(Command::Acquire(index, self.reply_send.clone())) + .unwrap(); // When the reply comes, we know we have the resource. self.reply_recv.recv().unwrap(); } diff --git a/samples/philosophers/src/condsync.rs b/samples/philosophers/src/condsync.rs index f8266e90..07255120 100644 --- a/samples/philosophers/src/condsync.rs +++ b/samples/philosophers/src/condsync.rs @@ -6,12 +6,9 @@ //! This implementation of the Fork synchronizer uses a single data object, protected by a //! `sync::Mutex`, and coordinated by a `sync::Condvar`. -use crate::{ - ForkSync, - NUM_PHIL, -}; -use zephyr::sync::Mutex; +use crate::{ForkSync, NUM_PHIL}; use zephyr::sync::Condvar; +use zephyr::sync::Mutex; // use zephyr::time::Forever; #[derive(Debug)] @@ -24,7 +21,7 @@ pub struct CondSync { impl CondSync { #[allow(dead_code)] - pub fn new() -> CondSync { + pub fn new() -> CondSync { CondSync { lock: Mutex::new([false; NUM_PHIL]), cond: Condvar::new(), diff --git a/samples/philosophers/src/dynsemsync.rs b/samples/philosophers/src/dynsemsync.rs index 8015ffe9..74b6f1ee 100644 --- a/samples/philosophers/src/dynsemsync.rs +++ b/samples/philosophers/src/dynsemsync.rs @@ -7,12 +7,10 @@ extern crate alloc; -use alloc::vec::Vec; use alloc::boxed::Box; +use alloc::vec::Vec; -use zephyr::{ - sync::Arc, sys::sync::Semaphore, time::Forever -}; +use zephyr::{sync::Arc, sys::sync::Semaphore, time::Forever}; use crate::{ForkSync, NUM_PHIL}; @@ -35,17 +33,19 @@ impl ForkSync for SemSync { #[allow(dead_code)] pub fn dyn_semaphore_sync() -> Vec> { - let forks = [(); NUM_PHIL].each_ref().map(|()| { - Arc::new(Semaphore::new(1, 1).unwrap()) - }); - - let syncers = (0..NUM_PHIL).map(|_| { - let syncer = SemSync { - forks: forks.clone(), - }; - let item = Box::new(syncer) as Box; - Arc::from(item) - }).collect(); + let forks = [(); NUM_PHIL] + .each_ref() + .map(|()| Arc::new(Semaphore::new(1, 1).unwrap())); + + let syncers = (0..NUM_PHIL) + .map(|_| { + let syncer = SemSync { + forks: forks.clone(), + }; + let item = Box::new(syncer) as Box; + Arc::from(item) + }) + .collect(); syncers } diff --git a/samples/philosophers/src/lib.rs b/samples/philosophers/src/lib.rs index dd027dc5..596c31d4 100644 --- a/samples/philosophers/src/lib.rs +++ b/samples/philosophers/src/lib.rs @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 #![no_std] - // Cargo tries to detect configs that have typos in them. Unfortunately, the Zephyr Kconfig system // uses a large number of Kconfigs and there is no easy way to know which ones might conceivably be // valid. This prevents a warning about each cfg that is used. @@ -13,31 +12,30 @@ extern crate alloc; #[allow(unused_imports)] use alloc::boxed::Box; use alloc::vec::Vec; -use zephyr::time::{Duration, sleep, Tick}; +use zephyr::time::{sleep, Duration, Tick}; use zephyr::{ - printkln, - kobj_define, - sys::uptime_get, + kobj_define, printkln, sync::{Arc, Mutex}, + sys::uptime_get, }; // These are optional, based on Kconfig, so allow them to be unused. #[allow(unused_imports)] -use crate::condsync::CondSync; +use crate::channel::get_channel_syncer; #[allow(unused_imports)] -use crate::sysmutex::SysMutexSync; +use crate::condsync::CondSync; #[allow(unused_imports)] -use crate::channel::get_channel_syncer; +use crate::dynsemsync::dyn_semaphore_sync; #[allow(unused_imports)] use crate::semsync::semaphore_sync; #[allow(unused_imports)] -use crate::dynsemsync::dyn_semaphore_sync; +use crate::sysmutex::SysMutexSync; mod channel; mod condsync; mod dynsemsync; -mod sysmutex; mod semsync; +mod sysmutex; /// How many philosophers. There will be the same number of forks. const NUM_PHIL: usize = 6; @@ -67,11 +65,13 @@ trait ForkSync: core::fmt::Debug + Sync + Send { #[no_mangle] extern "C" fn rust_main() { - printkln!("Hello world from Rust on {}", - zephyr::kconfig::CONFIG_BOARD); + printkln!("Hello world from Rust on {}", zephyr::kconfig::CONFIG_BOARD); printkln!("Time tick: {}", zephyr::time::SYS_FREQUENCY); - let stats = Arc::new(Mutex::new_from(Stats::default(), STAT_MUTEX.init_once(()).unwrap())); + let stats = Arc::new(Mutex::new_from( + Stats::default(), + STAT_MUTEX.init_once(()).unwrap(), + )); let syncers = get_syncer(); @@ -79,7 +79,9 @@ extern "C" fn rust_main() { for (i, syncer) in (0..NUM_PHIL).zip(syncers.into_iter()) { let child_stat = stats.clone(); - let thread = PHIL_THREADS[i].init_once(PHIL_STACKS[i].init_once(()).unwrap()).unwrap(); + let thread = PHIL_THREADS[i] + .init_once(PHIL_STACKS[i].init_once(()).unwrap()) + .unwrap(); thread.spawn(move || { phil_thread(i, syncer, child_stat); }); @@ -105,8 +107,7 @@ fn get_syncer() -> Vec> { #[cfg(CONFIG_SYNC_SYS_MUTEX)] fn get_syncer() -> Vec> { - let syncer = Box::new(SysMutexSync::new()) - as Box; + let syncer = Box::new(SysMutexSync::new()) as Box; let syncer: Arc = Arc::from(syncer); let mut result = Vec::new(); for _ in 0..NUM_PHIL { @@ -118,8 +119,7 @@ fn get_syncer() -> Vec> { #[cfg(CONFIG_SYNC_CONDVAR)] fn get_syncer() -> Vec> { // Condvar version - let syncer = Box::new(CondSync::new()) - as Box; + let syncer = Box::new(CondSync::new()) as Box; let syncer: Arc = Arc::from(syncer); let mut result = Vec::new(); for _ in 0..NUM_PHIL { @@ -141,7 +141,7 @@ fn phil_thread(n: usize, syncer: Arc, stats: Arc>) { // Per Dijkstra, the last phyilosopher needs to reverse forks, or we deadlock. (0, n) } else { - (n, n+1) + (n, n + 1) }; loop { @@ -202,7 +202,12 @@ impl Stats { } fn show(&self) { - printkln!("c:{:?}, e:{:?}, t:{:?}", self.count, self.eating, self.thinking); + printkln!( + "c:{:?}, e:{:?}, t:{:?}", + self.count, + self.eating, + self.thinking + ); } } diff --git a/samples/philosophers/src/semsync.rs b/samples/philosophers/src/semsync.rs index 889ab412..0cf901df 100644 --- a/samples/philosophers/src/semsync.rs +++ b/samples/philosophers/src/semsync.rs @@ -7,12 +7,10 @@ extern crate alloc; -use alloc::vec::Vec; use alloc::boxed::Box; +use alloc::vec::Vec; -use zephyr::{ - kobj_define, sync::Arc, sys::sync::Semaphore, time::Forever -}; +use zephyr::{kobj_define, sync::Arc, sys::sync::Semaphore, time::Forever}; use crate::{ForkSync, NUM_PHIL}; @@ -40,13 +38,15 @@ pub fn semaphore_sync() -> Vec> { Arc::new(m.init_once((1, 1)).unwrap()) }); - let syncers = (0..NUM_PHIL).map(|_| { - let syncer = SemSync { - forks: forks.clone(), - }; - let item = Box::new(syncer) as Box; - Arc::from(item) - }).collect(); + let syncers = (0..NUM_PHIL) + .map(|_| { + let syncer = SemSync { + forks: forks.clone(), + }; + let item = Box::new(syncer) as Box; + Arc::from(item) + }) + .collect(); syncers } diff --git a/samples/philosophers/src/sysmutex.rs b/samples/philosophers/src/sysmutex.rs index 969efb5f..c89f862f 100644 --- a/samples/philosophers/src/sysmutex.rs +++ b/samples/philosophers/src/sysmutex.rs @@ -6,10 +6,7 @@ //! This is a simple implementation of the Fork synchronizer that uses underlying Zephyr `k_mutex` //! wrapped in `sys::Mutex`. The ForkSync semantics map simply to these. -use crate::{ - ForkSync, - NUM_PHIL, -}; +use crate::{ForkSync, NUM_PHIL}; use zephyr::sys::sync::Mutex; use zephyr::time::Forever; @@ -25,10 +22,8 @@ pub struct SysMutexSync { impl SysMutexSync { #[allow(dead_code)] - pub fn new() -> SysMutexSync { - let locks = [(); NUM_PHIL].each_ref().map(|()| { - Mutex::new().unwrap() - }); + pub fn new() -> SysMutexSync { + let locks = [(); NUM_PHIL].each_ref().map(|()| Mutex::new().unwrap()); SysMutexSync { locks } } } diff --git a/tests/time/src/lib.rs b/tests/time/src/lib.rs index e8d1602d..2b1928e6 100644 --- a/tests/time/src/lib.rs +++ b/tests/time/src/lib.rs @@ -3,14 +3,11 @@ #![no_std] -use core::ffi::{ - c_char, - CStr, -}; +use core::ffi::{c_char, CStr}; use zephyr::printkln; -use zephyr::time::{Duration, Instant, Tick, Timeout}; use zephyr::raw::k_timeout_t; +use zephyr::time::{Duration, Instant, Tick, Timeout}; #[no_mangle] extern "C" fn rust_main() { @@ -29,7 +26,9 @@ fn check_conversions() { break; } let name = unsafe { - CStr::from_ptr(entry.name).to_str().expect("Invalid C string") + CStr::from_ptr(entry.name) + .to_str() + .expect("Invalid C string") }; printkln!("Testing: {}", name); @@ -57,8 +56,7 @@ fn check_conversions() { let value: Timeout = value.into(); let c_value = unsafe { ms_to_abs_timeout(entry.uvalue) }; if c_value.ticks != value.0.ticks { - printkln!("Mismatch C: {}, Rust: {}", - c_value.ticks, value.0.ticks); + printkln!("Mismatch C: {}, Rust: {}", c_value.ticks, value.0.ticks); } assert_eq!(c_value.ticks, value.0.ticks); } diff --git a/tests/timer/src/lib.rs b/tests/timer/src/lib.rs index 8676286a..a1282e30 100644 --- a/tests/timer/src/lib.rs +++ b/tests/timer/src/lib.rs @@ -11,7 +11,10 @@ use alloc::{boxed::Box, vec::Vec}; use rand::Rng; use rand_pcg::Pcg32; use zephyr::{ - printkln, sync::{atomic::AtomicUsize, Arc}, time::{Duration, NoWait, Tick}, timer::{Callback, CallbackTimer, SimpleTimer, StoppedTimer} + printkln, + sync::{atomic::AtomicUsize, Arc}, + time::{Duration, NoWait, Tick}, + timer::{Callback, CallbackTimer, SimpleTimer, StoppedTimer}, }; // Test the timers interface. There are a couple of things this tries to test: @@ -77,7 +80,9 @@ fn timer_test() { // Now that everything is done and cleaned up, allow a little time to pass to make sure there // are no stray timers. We can re-use the total test timer. - let mut total_test = total_test.stop().start_simple(Duration::millis_at_least(1), NoWait); + let mut total_test = total_test + .stop() + .start_simple(Duration::millis_at_least(1), NoWait); total_test.read_count_wait(); } diff --git a/zephyr-build/src/devicetree.rs b/zephyr-build/src/devicetree.rs index f2efa30c..e3200933 100644 --- a/zephyr-build/src/devicetree.rs +++ b/zephyr-build/src/devicetree.rs @@ -28,7 +28,7 @@ mod ordmap; mod output; mod parse; -pub use augment::{Augment, load_augments}; +pub use augment::{load_augments, Augment}; /// Representation of a parsed device tree. pub struct DeviceTree { @@ -97,8 +97,7 @@ impl DeviceTree { pub fn new, P2: AsRef>(dts_path: P1, dt_gen: P2) -> DeviceTree { let ords = OrdMap::new(dt_gen); - let dts = std::fs::read_to_string(dts_path) - .expect("Reading zephyr.dts file"); + let dts = std::fs::read_to_string(dts_path).expect("Reading zephyr.dts file"); let dt = parse::parse(&dts, &ords); // Walk the node tree, fixing any phandles to include their reference. @@ -167,32 +166,32 @@ impl Node { /// Returns the slice of values of a property with this name as `Some` or `None` if the property /// does not exist. fn get_property(&self, name: &str) -> Option<&[Value]> { - self.properties - .iter() - .find_map(|p| if p.name == name { Some(p.value.as_slice()) } else { None }) + self.properties.iter().find_map(|p| { + if p.name == name { + Some(p.value.as_slice()) + } else { + None + } + }) } /// Attempt to retrieve the named property, as a single entry of Words. fn get_words(&self, name: &str) -> Option<&[Word]> { - self.get_property(name) - .and_then(|p| { - match p { - &[Value::Words(ref w)] => Some(w.as_ref()), - _ => None, - } - }) + self.get_property(name).and_then(|p| match p { + &[Value::Words(ref w)] => Some(w.as_ref()), + _ => None, + }) } /// Get a property that consists of a single number. fn get_number(&self, name: &str) -> Option { - self.get_words(name) - .and_then(|p| { - if let &[Word::Number(n)] = p { - Some(n) - } else { - None - } - }) + self.get_words(name).and_then(|p| { + if let &[Word::Number(n)] = p { + Some(n) + } else { + None + } + }) } /// Get a property that consists of multiple numbers. @@ -210,14 +209,13 @@ impl Node { /// Get a property that is a single string. fn get_single_string(&self, name: &str) -> Option<&str> { - self.get_property(name) - .and_then(|p| { - if let &[Value::String(ref text)] = p { - Some(text.as_ref()) - } else { - None - } - }) + self.get_property(name).and_then(|p| { + if let &[Value::String(ref text)] = p { + Some(text.as_ref()) + } else { + None + } + }) } } @@ -253,8 +251,7 @@ impl Phandle { return; } - let node = labels.get(&self.name).cloned() - .expect("Missing phandle"); + let node = labels.get(&self.name).cloned().expect("Missing phandle"); *self.node.borrow_mut() = Some(node); } @@ -276,8 +273,7 @@ impl Word { // To avoid recursion, the debug printer for Phandle just prints the name. impl std::fmt::Debug for Phandle { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { - fmt - .debug_struct("Phandle") + fmt.debug_struct("Phandle") .field("name", &self.name) .finish_non_exhaustive() } diff --git a/zephyr-build/src/devicetree/augment.rs b/zephyr-build/src/devicetree/augment.rs index ec3bddb2..156a737b 100644 --- a/zephyr-build/src/devicetree/augment.rs +++ b/zephyr-build/src/devicetree/augment.rs @@ -87,10 +87,7 @@ pub enum Rule { /// Matches if this node has one of the listed compatible strings. The the 'level' property /// indicates how many levels up in the tree. Zero means match the current node, 1 means the /// parent node, and so on. - Compatible { - names: Vec, - level: usize, - }, + Compatible { names: Vec, level: usize }, /// Matches at the root of tree. Root, } @@ -143,9 +140,7 @@ pub enum Action { impl Action { fn generate(&self, _name: &Ident, node: &Node, tree: &DeviceTree) -> TokenStream { match self { - Action::Instance { raw, device } => { - raw.generate(node, device) - } + Action::Instance { raw, device } => raw.generate(node, device), Action::Labels => { let nodes = tree.labels.iter().map(|(k, v)| { let name = dt_to_lower_id(k); diff --git a/zephyr-build/src/devicetree/ordmap.rs b/zephyr-build/src/devicetree/ordmap.rs index 02bc0ec5..095c388a 100644 --- a/zephyr-build/src/devicetree/ordmap.rs +++ b/zephyr-build/src/devicetree/ordmap.rs @@ -2,7 +2,13 @@ //! //! The OrdMap provides a mapping between nodes on the devicetree, and their "ord" index. -use std::{collections::BTreeMap, fs::File, io::{BufRead, BufReader}, path::Path, str::FromStr}; +use std::{ + collections::BTreeMap, + fs::File, + io::{BufRead, BufReader}, + path::Path, + str::FromStr, +}; use regex::Regex; @@ -19,8 +25,7 @@ impl OrdMap { let mut c_name = "".to_string(); let mut dt_path = "".to_string(); - let fd = File::open(path) - .expect("Opening devicetree_generated.h"); + let fd = File::open(path).expect("Opening devicetree_generated.h"); for line in BufReader::new(fd).lines() { let line = line.expect("Reading from devicetree_generated.h"); diff --git a/zephyr-build/src/devicetree/output.rs b/zephyr-build/src/devicetree/output.rs index c5e6e455..bedb28f0 100644 --- a/zephyr-build/src/devicetree/output.rs +++ b/zephyr-build/src/devicetree/output.rs @@ -19,7 +19,6 @@ use super::{augment::Augment, DeviceTree, Node, Property, Value, Word}; impl DeviceTree { /// Generate a TokenStream for the Rust representation of this device tree. pub fn to_tokens(&self, augments: &[Box]) -> TokenStream { - // Root is a little special. Since we don't want a module for this (it will be provided // above where it is included, so it can get documentation and attributes), we use None for // the name. @@ -39,15 +38,19 @@ impl DeviceTree { Ok(()) } - fn node_walk(&self, node: &Node, name: Option<&str>, augments: &[Box]) -> TokenStream { - let children = node.children.iter().map(|child| { - self.node_walk(child.as_ref(), Some(&child.name), augments) - }); + fn node_walk( + &self, + node: &Node, + name: Option<&str>, + augments: &[Box], + ) -> TokenStream { + let children = node + .children + .iter() + .map(|child| self.node_walk(child.as_ref(), Some(&child.name), augments)); // Simplistic first pass, turn the properties into constents of the formatted text of the // property. - let props = node.properties.iter().map(|prop| { - self.property_walk(prop) - }); + let props = node.properties.iter().map(|prop| self.property_walk(prop)); let ord = node.ord; // Open the parent as a submodule. This is the same as 'super', so not particularly useful. @@ -114,7 +117,7 @@ impl DeviceTree { pub mod #tag { pub use #route::*; } - } + }; } _ => (), } @@ -172,7 +175,12 @@ impl Property { fn output_path(&self, write: &mut W, name: &str) -> Result<()> { if let Some(value) = self.get_single_value() { if let Value::Phandle(_) = value { - writeln!(write, "cargo:rustc-cfg=dt=\"{}::{}\"", name, fix_id(&self.name))?; + writeln!( + write, + "cargo:rustc-cfg=dt=\"{}::{}\"", + name, + fix_id(&self.name) + )?; } } Ok(()) diff --git a/zephyr-build/src/devicetree/parse.rs b/zephyr-build/src/devicetree/parse.rs index 44a42899..ecc75502 100644 --- a/zephyr-build/src/devicetree/parse.rs +++ b/zephyr-build/src/devicetree/parse.rs @@ -5,7 +5,10 @@ use std::{cell::RefCell, collections::BTreeMap, rc::Rc}; -use pest::{iterators::{Pair, Pairs}, Parser}; +use pest::{ + iterators::{Pair, Pairs}, + Parser, +}; use pest_derive::Parser; use crate::devicetree::Phandle; @@ -17,8 +20,7 @@ use super::{ordmap::OrdMap, DeviceTree, Node, Property, Value, Word}; pub struct Dts; pub fn parse(text: &str, ords: &OrdMap) -> DeviceTree { - let pairs = Dts::parse(Rule::file, text) - .expect("Parsing zephyr.dts"); + let pairs = Dts::parse(Rule::file, text).expect("Parsing zephyr.dts"); let b = TreeBuilder::new(ords); b.walk(pairs) @@ -123,7 +125,7 @@ fn decode_property(node: Pair<'_, Rule>) -> Property { // No escapes at this point. let text = pair.as_str(); // Remove the quotes. - let text = &text[1..text.len()-1]; + let text = &text[1..text.len() - 1]; value.push(Value::String(text.to_string())); } Rule::bytes => { @@ -132,7 +134,10 @@ fn decode_property(node: Pair<'_, Rule>) -> Property { r => panic!("rule: {:?}", r), } } - Property { name: name.unwrap(), value } + Property { + name: name.unwrap(), + value, + } } fn decode_words<'i>(node: Pair<'i, Rule>) -> Vec { @@ -205,7 +210,7 @@ impl<'a, 'b> LazyName<'a, 'b> { name: "/".to_string(), path: "/".to_string(), ord, - }) + }), } } else { LazyName { @@ -232,11 +237,7 @@ impl<'a, 'b> LazyName<'a, 'b> { path.push_str(&name); // println!("node: {:?}", path); let ord = self.ords.0[&path]; - self.info = Some(Info { - name, - path, - ord, - }); + self.info = Some(Info { name, path, ord }); } fn path_ref(&self) -> &str { diff --git a/zephyr-build/src/lib.rs b/zephyr-build/src/lib.rs index c4f02ef5..898e33a9 100644 --- a/zephyr-build/src/lib.rs +++ b/zephyr-build/src/lib.rs @@ -11,9 +11,9 @@ // This builds a program that is run on the compilation host before the code is compiled. It can // output configuration settings that affect the compilation. -use std::io::{BufRead, BufReader, Write}; use std::env; use std::fs::File; +use std::io::{BufRead, BufReader, Write}; use std::path::Path; use std::process::{Command, Stdio}; @@ -37,7 +37,7 @@ pub fn export_bool_kconfig() { let file = File::open(&dotconfig).expect("Unable to open dotconfig"); for line in BufReader::new(file).lines() { - let line = line.expect("reading line from dotconfig"); + let line = line.expect("reading line from dotconfig"); if let Some(caps) = config_y.captures(&line) { println!("cargo:rustc-cfg={}", &caps[1]); } @@ -66,16 +66,18 @@ pub fn build_kconfig_mod() { let line = line.expect("reading line from dotconfig"); if let Some(caps) = config_hex.captures(&line) { writeln!(&mut f, "#[allow(dead_code)]").unwrap(); - writeln!(&mut f, "pub const {}: usize = {};", - &caps[1], &caps[2]).unwrap(); + writeln!(&mut f, "pub const {}: usize = {};", &caps[1], &caps[2]).unwrap(); } else if let Some(caps) = config_int.captures(&line) { writeln!(&mut f, "#[allow(dead_code)]").unwrap(); - writeln!(&mut f, "pub const {}: isize = {};", - &caps[1], &caps[2]).unwrap(); + writeln!(&mut f, "pub const {}: isize = {};", &caps[1], &caps[2]).unwrap(); } else if let Some(caps) = config_str.captures(&line) { writeln!(&mut f, "#[allow(dead_code)]").unwrap(); - writeln!(&mut f, "pub const {}: &'static str = {};", - &caps[1], &caps[2]).unwrap(); + writeln!( + &mut f, + "pub const {}: &'static str = {};", + &caps[1], &caps[2] + ) + .unwrap(); } } } @@ -83,8 +85,8 @@ pub fn build_kconfig_mod() { /// Parse the finalized DTS file, generating the Rust devicetree file. fn import_dt() -> DeviceTree { let zephyr_dts = env::var("ZEPHYR_DTS").expect("ZEPHYR_DTS must be set"); - let gen_include = env::var("BINARY_DIR_INCLUDE_GENERATED") - .expect("BINARY_DIR_INCLUDE_GENERATED must be set"); + let gen_include = + env::var("BINARY_DIR_INCLUDE_GENERATED").expect("BINARY_DIR_INCLUDE_GENERATED must be set"); let generated = format!("{}/devicetree_generated.h", gen_include); DeviceTree::new(&zephyr_dts, generated) @@ -138,10 +140,7 @@ pub fn dt_cfgs() { /// Determine if `rustfmt` is in the path, and can be excecuted. Returns false on any kind of error. pub fn has_rustfmt() -> bool { - match Command::new("rustfmt") - .arg("--version") - .status() - { + match Command::new("rustfmt").arg("--version").status() { Ok(st) if st.success() => true, _ => false, } @@ -159,7 +158,10 @@ fn write_formatted(file: File, tokens: TokenStream) { .expect("Failed to run rustfmt"); // TODO: Handle the above failing. - let mut stdin = rustfmt.stdin.as_ref().expect("Stdin should have been opened by spawn"); + let mut stdin = rustfmt + .stdin + .as_ref() + .expect("Stdin should have been opened by spawn"); writeln!(stdin, "{}", tokens).expect("Writing to rustfmt"); match rustfmt.wait() { diff --git a/zephyr-sys/build.rs b/zephyr-sys/build.rs index efd8c8be..8a398bcc 100644 --- a/zephyr-sys/build.rs +++ b/zephyr-sys/build.rs @@ -55,7 +55,13 @@ fn main() -> Result<()> { // Bindgen everything. let bindings = Builder::default() - .header(Path::new("wrapper.h").canonicalize().unwrap().to_str().unwrap()) + .header( + Path::new("wrapper.h") + .canonicalize() + .unwrap() + .to_str() + .unwrap(), + ) .use_core() .clang_arg(&target_arg); let bindings = define_args(bindings, "-I", "INCLUDE_DIRS"); diff --git a/zephyr-sys/src/lib.rs b/zephyr-sys/src/lib.rs index 5f317d8c..6528b9af 100644 --- a/zephyr-sys/src/lib.rs +++ b/zephyr-sys/src/lib.rs @@ -7,16 +7,13 @@ //! Zephyr. #![no_std] - // Allow rust naming convention violations. #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] - // Zephyr makes use of zero-sized structs, which Rustc considers invalid. Suppress this warning. // Note, however, that this suppresses any warnings in the bindings about improper C types. #![allow(improper_ctypes)] - #![allow(rustdoc::broken_intra_doc_links)] #![allow(rustdoc::bare_urls)] diff --git a/zephyr/src/align.rs b/zephyr/src/align.rs index 8247d7a8..31d2c2c0 100644 --- a/zephyr/src/align.rs +++ b/zephyr/src/align.rs @@ -34,11 +34,12 @@ impl_alignas!(1, 2, 4, 8, 16, 32, 64, 128, 256); /// member of the struct. #[repr(transparent)] pub struct AlignAs([>::Aligned; 0]) - where +where AlignAsStruct: AlignAsTrait; impl AlignAs - where AlignAsStruct: AlignAsTrait +where + AlignAsStruct: AlignAsTrait, { /// Construct a new AlignAs. /// diff --git a/zephyr/src/device.rs b/zephyr/src/device.rs index bf4afec6..5206d720 100644 --- a/zephyr/src/device.rs +++ b/zephyr/src/device.rs @@ -10,8 +10,8 @@ use crate::sync::atomic::{AtomicBool, Ordering}; -pub mod gpio; pub mod flash; +pub mod gpio; // Allow dead code, because it isn't required for a given build to have any devices. /// Device uniqueness. diff --git a/zephyr/src/device/flash.rs b/zephyr/src/device/flash.rs index 83e277c3..5d76b422 100644 --- a/zephyr/src/device/flash.rs +++ b/zephyr/src/device/flash.rs @@ -3,8 +3,8 @@ // Note that currently, the flash partition shares the controller, so the underlying operations // are not actually safe. Need to rethink how to manage this. -use crate::raw; use super::Unique; +use crate::raw; /// A flash controller /// @@ -20,7 +20,10 @@ pub struct FlashController { impl FlashController { /// Constructor, intended to be called by devicetree generated code. #[allow(dead_code)] - pub(crate) unsafe fn new(unique: &Unique, device: *const raw::device) -> Option { + pub(crate) unsafe fn new( + unique: &Unique, + device: *const raw::device, + ) -> Option { if !unique.once() { return None; } @@ -45,7 +48,12 @@ pub struct FlashPartition { impl FlashPartition { /// Constructor, intended to be called by devicetree generated code. #[allow(dead_code)] - pub(crate) unsafe fn new(unique: &Unique, device: *const raw::device, offset: u32, size: u32) -> Option { + pub(crate) unsafe fn new( + unique: &Unique, + device: *const raw::device, + offset: u32, + size: u32, + ) -> Option { if !unique.once() { return None; } @@ -54,6 +62,10 @@ impl FlashPartition { // but in this case, we need one for each device, so just construct it here. // TODO: This is not actually safe. let controller = FlashController { device }; - Some(FlashPartition { controller, offset, size }) + Some(FlashPartition { + controller, + offset, + size, + }) } } diff --git a/zephyr/src/device/gpio.rs b/zephyr/src/device/gpio.rs index b9a31d3e..4cbd4f64 100644 --- a/zephyr/src/device/gpio.rs +++ b/zephyr/src/device/gpio.rs @@ -7,8 +7,8 @@ //! pervasively throughout Zephyr device drivers. As such, most of the calls in this module are //! unsafe. -use crate::raw; use super::Unique; +use crate::raw; /// Global instance to help make gpio in Rust slightly safer. /// @@ -60,9 +60,7 @@ impl Gpio { /// Verify that the device is ready for use. At a minimum, this means the device has been /// successfully initialized. pub fn is_ready(&self) -> bool { - unsafe { - raw::device_is_ready(self.device) - } + unsafe { raw::device_is_ready(self.device) } } } @@ -82,7 +80,12 @@ unsafe impl Send for GpioPin {} impl GpioPin { /// Constructor, used by the devicetree generated code. #[allow(dead_code)] - pub(crate) unsafe fn new(unique: &Unique, device: *const raw::device, pin: u32, dt_flags: u32) -> Option { + pub(crate) unsafe fn new( + unique: &Unique, + device: *const raw::device, + pin: u32, + dt_flags: u32, + ) -> Option { if !unique.once() { return None; } @@ -91,7 +94,7 @@ impl GpioPin { port: device, pin: pin as raw::gpio_pin_t, dt_flags: dt_flags as raw::gpio_dt_flags_t, - } + }, }) } @@ -112,9 +115,11 @@ impl GpioPin { pub unsafe fn configure(&mut self, _token: &mut GpioToken, extra_flags: raw::gpio_flags_t) { // TODO: Error? unsafe { - raw::gpio_pin_configure(self.pin.port, + raw::gpio_pin_configure( + self.pin.port, self.pin.pin, - self.pin.dt_flags as raw::gpio_flags_t | extra_flags); + self.pin.dt_flags as raw::gpio_flags_t | extra_flags, + ); } } diff --git a/zephyr/src/lib.rs b/zephyr/src/lib.rs index 4acda6a4..fbf51caf 100644 --- a/zephyr/src/lib.rs +++ b/zephyr/src/lib.rs @@ -72,7 +72,7 @@ use core::panic::PanicInfo; /// Override rust's panic. This simplistic initial version just hangs in a loop. #[panic_handler] -fn panic(info :&PanicInfo) -> ! { +fn panic(info: &PanicInfo) -> ! { #[cfg(CONFIG_PRINTK)] { printkln!("panic: {}", info); diff --git a/zephyr/src/logging/impl_printk.rs b/zephyr/src/logging/impl_printk.rs index fa9ef954..72a1d5c2 100644 --- a/zephyr/src/logging/impl_printk.rs +++ b/zephyr/src/logging/impl_printk.rs @@ -24,15 +24,11 @@ impl Log for PrintkLogger { // printing will be racy. Otherwise, the message will be broken into small chunks that are each // printed atomically. fn log(&self, record: &Record<'_>) { - printkln!("{}:{}: {}", - record.level(), - record.target(), - record.args()); + printkln!("{}:{}: {}", record.level(), record.target(), record.args()); } // Flush is not needed. - fn flush(&self) { - } + fn flush(&self) {} } static PRINTK_LOGGER: PrintkLogger = PrintkLogger; diff --git a/zephyr/src/logging/impl_zlog.rs b/zephyr/src/logging/impl_zlog.rs index 75295f2a..ec488d40 100644 --- a/zephyr/src/logging/impl_zlog.rs +++ b/zephyr/src/logging/impl_zlog.rs @@ -35,9 +35,7 @@ impl Log for ZlogLogger { // Zephyr doesn't have a separate trace, so fold that into debug. Level::Trace => raw::LOG_LEVEL_DBG, }; - let mut msg = format!("{}: {}", - record.target(), - record.args()); + let mut msg = format!("{}: {}", record.target(), record.args()); // Append a null so this is a valid C string. This lets us avoid an additional allocation // and copying. msg.push('\x00'); @@ -47,8 +45,7 @@ impl Log for ZlogLogger { } // Flush not needed. - fn flush(&self) { - } + fn flush(&self) {} } extern "C" { diff --git a/zephyr/src/object.rs b/zephyr/src/object.rs index a6d136ff..aab7be78 100644 --- a/zephyr/src/object.rs +++ b/zephyr/src/object.rs @@ -188,8 +188,8 @@ where KOBJ_UNINITIALIZED, KOBJ_INITING, Ordering::AcqRel, - Ordering::Acquire) - { + Ordering::Acquire, + ) { return None; } let result = self.get_wrapped(args); @@ -401,7 +401,7 @@ macro_rules! _kobj_stack { [$crate::sys::thread::RealStaticThreadStack<{$crate::sys::thread::stack_len($size)}>; $asize] = unsafe { ::core::mem::zeroed() }; - $v static $name: + $v static $name: [$crate::_export::KStaticThreadStack; $asize] = $crate::_export::KStaticThreadStack::new_from_array(&[< $name _REAL >]); } diff --git a/zephyr/src/printk.rs b/zephyr/src/printk.rs index 8a281df5..452f2eb0 100644 --- a/zephyr/src/printk.rs +++ b/zephyr/src/printk.rs @@ -5,12 +5,7 @@ //! //! This uses the `k_str_out` syscall, which is part of printk to output to the console. -use core::fmt::{ - Arguments, - Result, - Write, - write, -}; +use core::fmt::{write, Arguments, Result, Write}; /// Print to Zephyr's console, without a newline. /// diff --git a/zephyr/src/sync.rs b/zephyr/src/sync.rs index 977433bb..8ded9963 100644 --- a/zephyr/src/sync.rs +++ b/zephyr/src/sync.rs @@ -30,17 +30,8 @@ pub use portable_atomic_util::Arc; mod mutex; -pub use mutex::{ - Mutex, - MutexGuard, - Condvar, - LockResult, - TryLockResult, -}; +pub use mutex::{Condvar, LockResult, Mutex, MutexGuard, TryLockResult}; mod spinmutex; -pub use spinmutex::{ - SpinMutex, - SpinMutexGuard, -}; +pub use spinmutex::{SpinMutex, SpinMutexGuard}; diff --git a/zephyr/src/sync/channel.rs b/zephyr/src/sync/channel.rs index 7dba4bb5..410577a6 100644 --- a/zephyr/src/sync/channel.rs +++ b/zephyr/src/sync/channel.rs @@ -70,13 +70,13 @@ pub fn unbounded_from(queue: Queue) -> (Sender, Receiver) { flavor: SenderFlavor::Unbounded { queue: s, _phantom: PhantomData, - } + }, }; let r = Receiver { flavor: ReceiverFlavor::Unbounded { queue: r, _phantom: PhantomData, - } + }, }; (s, r) } @@ -130,10 +130,7 @@ pub struct Message { impl Message { fn new(data: T) -> Message { - Message { - _private: 0, - data, - } + Message { _private: 0, data } } } @@ -155,7 +152,8 @@ impl Sender { /// For unbounded channels, this will perform an allocation (and always send immediately). For /// bounded channels, no allocation will be performed. pub fn send_timeout(&self, msg: T, timeout: D) -> Result<(), SendError> - where D: Into, + where + D: Into, { match &self.flavor { SenderFlavor::Unbounded { queue, .. } => { @@ -233,15 +231,11 @@ impl Drop for Sender { impl Clone for Sender { fn clone(&self) -> Self { let flavor = match &self.flavor { - SenderFlavor::Unbounded { queue, .. } => { - SenderFlavor::Unbounded { - queue: queue.acquire(), - _phantom: PhantomData, - } - } - SenderFlavor::Bounded(chan) => { - SenderFlavor::Bounded(chan.acquire()) - } + SenderFlavor::Unbounded { queue, .. } => SenderFlavor::Unbounded { + queue: queue.acquire(), + _phantom: PhantomData, + }, + SenderFlavor::Bounded(chan) => SenderFlavor::Bounded(chan.acquire()), }; Sender { flavor } @@ -281,7 +275,8 @@ impl Receiver { /// operation can proceed or the operation times out. /// wake up and return an error. pub fn recv_timeout(&self, timeout: D) -> Result - where D: Into, + where + D: Into, { match &self.flavor { ReceiverFlavor::Unbounded { queue, .. } => { @@ -369,15 +364,11 @@ impl Drop for Receiver { impl Clone for Receiver { fn clone(&self) -> Self { let flavor = match &self.flavor { - ReceiverFlavor::Unbounded { queue, .. } => { - ReceiverFlavor::Unbounded { - queue: queue.acquire(), - _phantom: PhantomData, - } - } - ReceiverFlavor::Bounded(chan) => { - ReceiverFlavor::Bounded(chan.acquire()) - } + ReceiverFlavor::Unbounded { queue, .. } => ReceiverFlavor::Unbounded { + queue: queue.acquire(), + _phantom: PhantomData, + }, + ReceiverFlavor::Bounded(chan) => ReceiverFlavor::Bounded(chan.acquire()), }; Receiver { flavor } @@ -435,10 +426,8 @@ struct Bounded { impl Bounded { fn new(cap: usize) -> Self { let slots: Box<[Slot]> = (0..cap) - .map(|_| { - UnsafeCell::new(MaybeUninit::uninit()) - }) - .collect(); + .map(|_| UnsafeCell::new(MaybeUninit::uninit())) + .collect(); let slots = Box::into_pin(slots); let free = Queue::new().unwrap(); @@ -452,7 +441,11 @@ impl Bounded { } } - Bounded { _slots: slots, free, chan } + Bounded { + _slots: slots, + free, + chan, + } } } diff --git a/zephyr/src/sync/channel/counter.rs b/zephyr/src/sync/channel/counter.rs index 4b28ae84..f72b5b1f 100644 --- a/zephyr/src/sync/channel/counter.rs +++ b/zephyr/src/sync/channel/counter.rs @@ -3,13 +3,12 @@ // This file is taken from crossbeam-channels, with modifications to be nostd. - extern crate alloc; +use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use alloc::boxed::Box; use core::ops; use core::ptr::NonNull; -use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; /// Reference counter internals. struct Counter { diff --git a/zephyr/src/sync/mutex.rs b/zephyr/src/sync/mutex.rs index 6cd21acb..c8431c73 100644 --- a/zephyr/src/sync/mutex.rs +++ b/zephyr/src/sync/mutex.rs @@ -11,8 +11,8 @@ use core::{ ops::{Deref, DerefMut}, }; -use crate::time::{Forever, NoWait}; use crate::sys::sync as sys; +use crate::time::{Forever, NoWait}; /// Until poisoning is implemented, mutexes never return an error, and we just get back the guard. pub type LockResult = Result; @@ -90,7 +90,10 @@ impl Mutex { /// sys Mutex will be taken by this structure. It is safe to share the underlying Mutex between /// different items, but without careful use, it is easy to deadlock, so it is not recommended. pub const fn new_from(t: T, raw_mutex: sys::Mutex) -> Mutex { - Mutex { inner: raw_mutex, data: UnsafeCell::new(t) } + Mutex { + inner: raw_mutex, + data: UnsafeCell::new(t), + } } /// Construct a new Mutex, dynamically allocating the underlying sys Mutex. @@ -114,9 +117,7 @@ impl Mutex { pub fn lock(&self) -> LockResult> { // With `Forever`, should never return an error. self.inner.lock(Forever).unwrap(); - unsafe { - Ok(MutexGuard::new(self)) - } + unsafe { Ok(MutexGuard::new(self)) } } /// Attempts to acquire this lock. @@ -127,16 +128,10 @@ impl Mutex { /// This function does not block. pub fn try_lock(&self) -> TryLockResult> { match self.inner.lock(NoWait) { - Ok(()) => { - unsafe { - Ok(MutexGuard::new(self)) - } - } + Ok(()) => unsafe { Ok(MutexGuard::new(self)) }, // TODO: It might be better to distinguish these errors, and only return the WouldBlock // if that is the corresponding error. But, the lock shouldn't fail in Zephyr. - Err(_) => { - Err(TryLockError::WouldBlock) - } + Err(_) => Err(TryLockError::WouldBlock), } } } @@ -144,7 +139,10 @@ impl Mutex { impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> { unsafe fn new(lock: &'mutex Mutex) -> MutexGuard<'mutex, T> { // poison todo - MutexGuard { lock, _nosend: PhantomData } + MutexGuard { + lock, + _nosend: PhantomData, + } } } @@ -152,9 +150,7 @@ impl Deref for MutexGuard<'_, T> { type Target = T; fn deref(&self) -> &T { - unsafe { - &*self.lock.data.get() - } + unsafe { &*self.lock.data.get() } } } diff --git a/zephyr/src/sync/spinmutex.rs b/zephyr/src/sync/spinmutex.rs index 49ee444f..a741022b 100644 --- a/zephyr/src/sync/spinmutex.rs +++ b/zephyr/src/sync/spinmutex.rs @@ -18,7 +18,13 @@ //! used with a `Semaphore` to allow clients to be waken, but this usage is racey, and if not done //! carefully can result uses of the semaphore not waking. -use core::{cell::UnsafeCell, convert::Infallible, fmt, marker::PhantomData, ops::{Deref, DerefMut}}; +use core::{ + cell::UnsafeCell, + convert::Infallible, + fmt, + marker::PhantomData, + ops::{Deref, DerefMut}, +}; use crate::raw; @@ -114,21 +120,22 @@ impl SpinMutex { pub fn try_lock(&self) -> SpinTryLockResult> { let mut key = raw::k_spinlock_key_t { key: 0 }; match unsafe { raw::k_spin_trylock(self.inner.get(), &mut key) } { - 0 => { - unsafe { - Ok(SpinMutexGuard::new(self, key)) - } - } - _ => { - Err(SpinTryLockError::WouldBlock) - } + 0 => unsafe { Ok(SpinMutexGuard::new(self, key)) }, + _ => Err(SpinTryLockError::WouldBlock), } } } impl<'mutex, T: ?Sized> SpinMutexGuard<'mutex, T> { - unsafe fn new(lock: &'mutex SpinMutex, key: raw::k_spinlock_key_t) -> SpinMutexGuard<'mutex, T> { - SpinMutexGuard { lock, key, _nosend: PhantomData } + unsafe fn new( + lock: &'mutex SpinMutex, + key: raw::k_spinlock_key_t, + ) -> SpinMutexGuard<'mutex, T> { + SpinMutexGuard { + lock, + key, + _nosend: PhantomData, + } } } @@ -136,9 +143,7 @@ impl Deref for SpinMutexGuard<'_, T> { type Target = T; fn deref(&self) -> &T { - unsafe { - &*self.lock.data.get() - } + unsafe { &*self.lock.data.get() } } } diff --git a/zephyr/src/sys.rs b/zephyr/src/sys.rs index f85069a1..7f127d85 100644 --- a/zephyr/src/sys.rs +++ b/zephyr/src/sys.rs @@ -36,9 +36,7 @@ pub const K_NO_WAIT: k_timeout_t = k_timeout_t { ticks: 0 }; /// Direct Zephyr call. Precision is limited by the system tick timer. #[inline] pub fn uptime_get() -> i64 { - unsafe { - crate::raw::k_uptime_get() - } + unsafe { crate::raw::k_uptime_get() } } pub mod critical { @@ -56,7 +54,7 @@ pub mod critical { use core::{ffi::c_int, ptr::addr_of_mut}; use critical_section::RawRestoreState; - use zephyr_sys::{k_spinlock, k_spin_lock, k_spin_unlock, k_spinlock_key_t}; + use zephyr_sys::{k_spin_lock, k_spin_unlock, k_spinlock, k_spinlock_key_t}; struct ZephyrCriticalSection; critical_section::set_impl!(ZephyrCriticalSection); @@ -71,10 +69,12 @@ pub mod critical { } unsafe fn release(token: RawRestoreState) { - k_spin_unlock(addr_of_mut!(LOCK), - k_spinlock_key_t { - key: token as c_int, - }); + k_spin_unlock( + addr_of_mut!(LOCK), + k_spinlock_key_t { + key: token as c_int, + }, + ); } } } diff --git a/zephyr/src/sys/queue.rs b/zephyr/src/sys/queue.rs index 943733f0..f52fa57e 100644 --- a/zephyr/src/sys/queue.rs +++ b/zephyr/src/sys/queue.rs @@ -9,12 +9,7 @@ use core::fmt; #[cfg(CONFIG_RUST_ALLOC)] use core::mem; -use zephyr_sys::{ - k_queue, - k_queue_init, - k_queue_append, - k_queue_get, -}; +use zephyr_sys::{k_queue, k_queue_append, k_queue_get, k_queue_init}; #[cfg(CONFIG_RUST_ALLOC)] use crate::error::Result; @@ -26,10 +21,10 @@ pub struct Queue { item: Fixed, } -unsafe impl Sync for StaticKernelObject { } +unsafe impl Sync for StaticKernelObject {} -unsafe impl Sync for Queue { } -unsafe impl Send for Queue { } +unsafe impl Sync for Queue {} +unsafe impl Send for Queue {} impl Queue { /// Create a new Queue, dynamically allocated. @@ -70,7 +65,8 @@ impl Queue { /// [`NoWait`]: crate::time::NoWait /// [`Duration`]: crate::time::Duration pub unsafe fn recv(&self, timeout: T) -> *mut c_void - where T: Into + where + T: Into, { let timeout: Timeout = timeout.into(); k_queue_get(self.item.get(), timeout.0) diff --git a/zephyr/src/sys/sync.rs b/zephyr/src/sys/sync.rs index 19d459e6..ef88234b 100644 --- a/zephyr/src/sys/sync.rs +++ b/zephyr/src/sys/sync.rs @@ -33,13 +33,5 @@ pub mod mutex; pub mod semaphore; -pub use mutex::{ - Condvar, - StaticCondvar, - Mutex, - StaticMutex, -}; -pub use semaphore::{ - Semaphore, - StaticSemaphore, -}; +pub use mutex::{Condvar, Mutex, StaticCondvar, StaticMutex}; +pub use semaphore::{Semaphore, StaticSemaphore}; diff --git a/zephyr/src/sys/sync/mutex.rs b/zephyr/src/sys/sync/mutex.rs index 46eb57b0..ae19723b 100644 --- a/zephyr/src/sys/sync/mutex.rs +++ b/zephyr/src/sys/sync/mutex.rs @@ -8,30 +8,19 @@ //! //! [`object`]: crate::object -use core::fmt; -#[cfg(CONFIG_RUST_ALLOC)] -use core::mem; +use crate::object::{Fixed, StaticKernelObject, Wrapped}; +use crate::sys::K_FOREVER; use crate::{ - error::{Result, to_result_void}, + error::{to_result_void, Result}, raw::{ - k_condvar, - k_condvar_init, - k_condvar_broadcast, - k_condvar_signal, - k_condvar_wait, - k_mutex, - k_mutex_init, - k_mutex_lock, - k_mutex_unlock, + k_condvar, k_condvar_broadcast, k_condvar_init, k_condvar_signal, k_condvar_wait, k_mutex, + k_mutex_init, k_mutex_lock, k_mutex_unlock, }, time::Timeout, }; -use crate::object::{ - Fixed, - StaticKernelObject, - Wrapped, -}; -use crate::sys::K_FOREVER; +use core::fmt; +#[cfg(CONFIG_RUST_ALLOC)] +use core::mem; /// A Zephyr `k_mutux` usable from safe Rust code. /// @@ -79,7 +68,8 @@ impl Mutex { /// acquired, and an error indicating a timeout (Zephyr returns different errors depending on /// the reason). pub fn lock(&self, timeout: T) -> Result<()> - where T: Into, + where + T: Into, { let timeout: Timeout = timeout.into(); to_result_void(unsafe { k_mutex_lock(self.item.get(), timeout.0) }) @@ -94,7 +84,6 @@ impl Mutex { } } - /// A static Zephyr `k_mutex` /// /// This is intended to be used from within the `kobj_define!` macro. It declares a static @@ -123,7 +112,7 @@ impl Wrapped for StaticKernelObject { unsafe { k_mutex_init(ptr); } - Mutex { + Mutex { item: Fixed::Static(ptr), } } @@ -146,7 +135,7 @@ pub struct Condvar { #[doc(hidden)] pub type StaticCondvar = StaticKernelObject; -unsafe impl Sync for StaticKernelObject { } +unsafe impl Sync for StaticKernelObject {} unsafe impl Sync for Condvar {} unsafe impl Send for Condvar {} @@ -173,19 +162,25 @@ impl Condvar { /// [`sync::Condvar`]: http://www.example.com/TODO // /// [`sync::Condvar`]: crate::sync::Condvar pub fn wait(&self, lock: &Mutex) { - unsafe { k_condvar_wait(self.item.get(), lock.item.get(), K_FOREVER); } + unsafe { + k_condvar_wait(self.item.get(), lock.item.get(), K_FOREVER); + } } // TODO: timeout. /// Wake a single thread waiting on this condition variable. pub fn notify_one(&self) { - unsafe { k_condvar_signal(self.item.get()); } + unsafe { + k_condvar_signal(self.item.get()); + } } /// Wake all threads waiting on this condition variable. pub fn notify_all(&self) { - unsafe { k_condvar_broadcast(self.item.get()); } + unsafe { + k_condvar_broadcast(self.item.get()); + } } } diff --git a/zephyr/src/sys/sync/semaphore.rs b/zephyr/src/sys/sync/semaphore.rs index 1aafd8a6..21f99efc 100644 --- a/zephyr/src/sys/sync/semaphore.rs +++ b/zephyr/src/sys/sync/semaphore.rs @@ -19,9 +19,7 @@ use core::mem; use crate::{ error::{to_result_void, Result}, object::{Fixed, StaticKernelObject, Wrapped}, - raw::{ - k_sem, k_sem_count_get, k_sem_give, k_sem_init, k_sem_reset, k_sem_take - }, + raw::{k_sem, k_sem_count_get, k_sem_give, k_sem_init, k_sem_reset, k_sem_take}, time::Timeout, }; @@ -59,12 +57,11 @@ impl Semaphore { /// /// [`NoWait`]: crate::time::NoWait pub fn take(&self, timeout: T) -> Result<()> - where T: Into, + where + T: Into, { let timeout: Timeout = timeout.into(); - let ret = unsafe { - k_sem_take(self.item.get(), timeout.0) - }; + let ret = unsafe { k_sem_take(self.item.get(), timeout.0) }; to_result_void(ret) } @@ -73,9 +70,7 @@ impl Semaphore { /// This routine gives to the semaphore, unless the semaphore is already at its maximum /// permitted count. pub fn give(&self) { - unsafe { - k_sem_give(self.item.get()) - } + unsafe { k_sem_give(self.item.get()) } } /// Resets a semaphor's count to zero. @@ -85,18 +80,14 @@ impl Semaphore { /// /// [`take`]: Self::take pub fn reset(&mut self) { - unsafe { - k_sem_reset(self.item.get()) - } + unsafe { k_sem_reset(self.item.get()) } } /// Get a semaphore's count. /// /// Returns the current count. pub fn count_get(&mut self) -> usize { - unsafe { - k_sem_count_get(self.item.get()) as usize - } + unsafe { k_sem_count_get(self.item.get()) as usize } } } diff --git a/zephyr/src/sys/thread.rs b/zephyr/src/sys/thread.rs index 870bc005..92999ff0 100644 --- a/zephyr/src/sys/thread.rs +++ b/zephyr/src/sys/thread.rs @@ -40,21 +40,23 @@ extern crate alloc; #[cfg(CONFIG_RUST_ALLOC)] use alloc::boxed::Box; -use core::{cell::UnsafeCell, ffi::{c_int, c_void, CStr}, mem}; +use core::{ + cell::UnsafeCell, + ffi::{c_int, c_void, CStr}, + mem, +}; +use super::K_NO_WAIT; use zephyr_sys::{ - k_tid_t, - k_thread, - k_thread_entry_t, - k_thread_create, - k_thread_name_set, - z_thread_stack_element, - ZR_STACK_ALIGN, - ZR_STACK_RESERVED, + k_thread, k_thread_create, k_thread_entry_t, k_thread_name_set, k_tid_t, + z_thread_stack_element, ZR_STACK_ALIGN, ZR_STACK_RESERVED, }; -use super::K_NO_WAIT; -use crate::{align::AlignAs, object::{StaticKernelObject, Wrapped}, sync::atomic::AtomicUsize}; +use crate::{ + align::AlignAs, + object::{StaticKernelObject, Wrapped}, + sync::atomic::AtomicUsize, +}; /// Adjust the stack size for alignment. Note that, unlike the C code, we don't include the /// reservation in this, as it has its own fields in the struct. @@ -225,12 +227,13 @@ impl Thread { /// Simple thread spawn. This is unsafe because of the raw values being used. This can be /// useful in systems without an allocator defined. - pub unsafe fn simple_spawn(mut self, - child: k_thread_entry_t, - p1: *mut c_void, - p2: *mut c_void, - p3: *mut c_void) - { + pub unsafe fn simple_spawn( + mut self, + child: k_thread_entry_t, + p1: *mut c_void, + p2: *mut c_void, + p3: *mut c_void, + ) { let tid = k_thread_create( self.raw, self.stack.base, @@ -241,7 +244,8 @@ impl Thread { p3, self.priority, self.options, - K_NO_WAIT); + K_NO_WAIT, + ); self.set_thread_name(tid); } @@ -254,9 +258,7 @@ impl Thread { use core::ptr::null_mut; let child: closure::Closure = Box::new(child); - let child = Box::into_raw(Box::new(closure::ThreadData { - closure: child, - })); + let child = Box::into_raw(Box::new(closure::ThreadData { closure: child })); unsafe { let tid = k_thread_create( self.raw, @@ -268,7 +270,8 @@ impl Thread { null_mut(), self.priority, self.options, - K_NO_WAIT); + K_NO_WAIT, + ); self.set_thread_name(tid); } @@ -404,7 +407,7 @@ pub struct StackToken { // possible to implement safe static threads and other data structures in Zephyr. /// A Statically defined Zephyr `k_thread` object to be used from Rust. -/// +/// /// This should be used in a manner similar to: /// ``` /// const MY_STACK_SIZE: usize = 4096; diff --git a/zephyr/src/time.rs b/zephyr/src/time.rs index e1d6eafb..9eee52db 100644 --- a/zephyr/src/time.rs +++ b/zephyr/src/time.rs @@ -24,7 +24,7 @@ //! by non-constant values). Similarly, the `fugit` crate offers constructors that aim to result //! in constants when possible, avoiding costly division operations. -use zephyr_sys::{k_timeout_t, k_ticks_t}; +use zephyr_sys::{k_ticks_t, k_timeout_t}; use core::fmt::Debug; @@ -89,7 +89,9 @@ impl From for Timeout { let ticks: k_ticks_t = checked_cast(value.ticks()); debug_assert_ne!(ticks, crate::sys::K_FOREVER.ticks); debug_assert_ne!(ticks, crate::sys::K_NO_WAIT.ticks); - Timeout(k_timeout_t { ticks: -1 - 1 - ticks }) + Timeout(k_timeout_t { + ticks: -1 - 1 - ticks, + }) } } @@ -116,7 +118,8 @@ impl From for Timeout { /// Put the current thread to sleep, for the given duration. Uses `k_sleep` for the actual sleep. /// Returns a duration roughly representing the remaining amount of time if the sleep was woken. pub fn sleep(timeout: T) -> Duration - where T: Into, +where + T: Into, { let timeout: Timeout = timeout.into(); let rest = unsafe { crate::raw::k_sleep(timeout.0) }; diff --git a/zephyr/src/timer.rs b/zephyr/src/timer.rs index 658911bd..a8606a35 100644 --- a/zephyr/src/timer.rs +++ b/zephyr/src/timer.rs @@ -43,14 +43,8 @@ use core::{fmt, mem}; use crate::object::{Fixed, StaticKernelObject, Wrapped}; use crate::raw::{ - k_timer, - k_timer_init, - k_timer_start, - k_timer_status_get, - k_timer_status_sync, - k_timer_stop, - k_timer_user_data_get, - k_timer_user_data_set, + k_timer, k_timer_init, k_timer_start, k_timer_status_get, k_timer_status_sync, k_timer_stop, + k_timer_user_data_get, k_timer_user_data_set, }; use crate::time::Timeout; @@ -86,7 +80,11 @@ impl StoppedTimer { /// /// [`NoWait`]: crate::time::NoWait /// [`Forever`]: crate::time::Forever - pub fn start_simple(self, delay: impl Into, period: impl Into) -> SimpleTimer { + pub fn start_simple( + self, + delay: impl Into, + period: impl Into, + ) -> SimpleTimer { unsafe { // SAFETY: The timer will be registered with Zephyr, using fields within the struct. // The `Fixed` type takes care of ensuring that the memory is not used. Drop will call @@ -94,7 +92,9 @@ impl StoppedTimer { k_timer_start(self.item.get(), delay.into().0, period.into().0); } - SimpleTimer { item: Some(self.item) } + SimpleTimer { + item: Some(self.item), + } } /// Start the timer in "callback" mode. @@ -117,16 +117,17 @@ impl StoppedTimer { /// [`SpinMutex`]: crate::sync::SpinMutex /// [`Semaphore`]: crate::sys::sync::Semaphore /// [`Sender`]: crate::sync::channel::Sender - pub fn start_callback(self, - callback: Callback, - delay: impl Into, - period: impl Into, + pub fn start_callback( + self, + callback: Callback, + delay: impl Into, + period: impl Into, ) -> Pin>> - where T: Send + Sync + where + T: Send + Sync, { CallbackTimer::new(self, callback, delay, period) } - } impl fmt::Debug for StoppedTimer { @@ -223,7 +224,10 @@ impl SimpleTimer { /// Get the item pointer, assuming it is still present. fn item_ptr(&self) -> *mut k_timer { - self.item.as_ref().expect("Use of SimpleTimer after stop").get() + self.item + .as_ref() + .expect("Use of SimpleTimer after stop") + .get() } /// Stop the timer. @@ -294,10 +298,11 @@ pub struct CallbackTimer { } impl CallbackTimer { - fn new(item: StoppedTimer, - callback: Callback, - delay: impl Into, - period: impl Into, + fn new( + item: StoppedTimer, + callback: Callback, + delay: impl Into, + period: impl Into, ) -> Pin>> { let this = Box::pin(CallbackTimer { item: Some(item.item), @@ -342,7 +347,10 @@ impl CallbackTimer { /// Get the item pointer, assuming it is still present. fn item_ptr(&self) -> *mut k_timer { - self.item.as_ref().expect("Use of SimpleTimer after stop").get() + self.item + .as_ref() + .expect("Use of SimpleTimer after stop") + .get() } /// Stop the timer.