Skip to content

Commit

Permalink
Lift singleton from cortex-m
Browse files Browse the repository at this point in the history
  • Loading branch information
bugadani committed Oct 16, 2024
1 parent 3e25d9a commit 8a61962
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 10 deletions.
1 change: 1 addition & 0 deletions xtensa-lx/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ keywords = ["lx", "peripheral", "register", "xtensa"]
links = "xtensa-lx"

[dependencies]
critical-section = "1.0.0"
document-features = "0.2.10"

[features]
7 changes: 7 additions & 0 deletions xtensa-lx/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,10 @@ pub fn is_debugger_attached() -> bool {
pub fn debug_break() {
unsafe { asm!("break 1, 15", options(nostack)) };
}

/// Used to reexport items for use in macros. Do not use directly.
/// Not covered by semver guarantees.
#[doc(hidden)]
pub mod _export {
pub use critical_section;
}
24 changes: 14 additions & 10 deletions xtensa-lx/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,27 +26,31 @@
/// ```
#[macro_export]
macro_rules! singleton {
(: $ty:ty = $expr:expr) => {
$crate::interrupt::free(|_| {
static mut VAR: Option<$ty> = None;
($(#[$meta:meta])* $name:ident: $ty:ty = $expr:expr) => {
$crate::_export::critical_section::with(|_| {
// this is a tuple of a MaybeUninit and a bool because using an Option here is
// problematic: Due to niche-optimization, an Option could end up producing a non-zero
// initializer value which would move the entire static from `.bss` into `.data`...
$(#[$meta])*
static mut $name: (::core::mem::MaybeUninit<$ty>, bool) =
(::core::mem::MaybeUninit::uninit(), false);

#[allow(unsafe_code)]
let used = unsafe { VAR.is_some() };
let used = unsafe { $name.1 };
if used {
None
} else {
let expr = $expr;

#[allow(unsafe_code)]
unsafe {
VAR = Some(expr)
}

#[allow(unsafe_code)]
unsafe {
VAR.as_mut()
$name.1 = true;
Some($name.0.write(expr))
}
}
})
};
($(#[$meta:meta])* : $ty:ty = $expr:expr) => {
$crate::singleton!($(#[$meta])* VAR: $ty = $expr)
};
}

0 comments on commit 8a61962

Please sign in to comment.