Skip to content

[RFC] initialize singletons at runtime #81

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 25, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ version = "0.4.2"
aligned = "0.1.1"
bare-metal = "0.1.0"
volatile-register = "0.2.0"
untagged-option = "0.1.1"

[features]
cm7-r0p1 = []
cm7-r0p1 = []
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

extern crate aligned;
extern crate bare_metal;
extern crate untagged_option;
extern crate volatile_register;

#[macro_use]
Expand All @@ -31,3 +32,4 @@ pub mod peripheral;
pub mod register;

pub use peripheral::Peripherals;
pub use untagged_option::UntaggedOption;
52 changes: 47 additions & 5 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,59 @@ macro_rules! iprintln {
#[macro_export]
macro_rules! singleton {
(: $ty:ty = $expr:expr) => {
$crate::interrupt::free(|_| unsafe {
$crate::interrupt::free(|_| {
static mut USED: bool = false;
static mut VAR: $ty = $expr;
static mut VAR: $crate::UntaggedOption<$ty> = $crate::UntaggedOption { none: () };

if USED {

#[allow(unsafe_code)]
let used = unsafe { USED };
if used {
None
} else {
USED = true;
let var: &'static mut _ = &mut VAR;
#[allow(unsafe_code)]
unsafe { USED = true }

let expr = $expr;

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

#[allow(unsafe_code)]
let var: &'static mut _ = unsafe { &mut VAR.some };

Some(var)
}
})
}
}


/// ``` compile_fail
/// #[macro_use(singleton)]
/// extern crate cortex_m;
///
/// fn main() {}
///
/// fn foo() {
/// // check that the call to `uninitialized` requires unsafe
/// singleton!(: u8 = std::mem::uninitialized());
/// }
/// ```
#[allow(dead_code)]
const CFAIL: () = ();

/// ```
/// #![deny(unsafe_code)]
/// #[macro_use(singleton)]
/// extern crate cortex_m;
///
/// fn main() {}
///
/// fn foo() {
/// // check that calls to `singleton!` don't trip the `unsafe_code` lint
/// singleton!(: u8 = 0);
/// }
/// ```
#[allow(dead_code)]
const CPASS: () = ();