Skip to content

Commit 19125ac

Browse files
committed
macros: Allow setting a name for singleton!() statics
Right now, the `singleton!()` macro always creates a static named `VAR`. This is annoying when digging through objdump output or digging into memory with a debugger because it is hard to see what singleton you're looking at when they are all called `<...>::{{closure}}::VAR`. To make it a bit nicer, allow setting the name of the generated static to some meaningful identifier which can then be cross-referenced in debugger output, for example with singleton!(FOO_BUFFER: [u8; 1024] = [0u8; 1024]); There is no other side-effects to this change - the identifier is never visible to other code because it is still contained in the closure of the macro.
1 parent 50c7fd3 commit 19125ac

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

src/macros.rs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,12 @@ macro_rules! iprintln {
3030
/// `None` variant the caller must ensure that the macro is called from a function that's executed
3131
/// at most once in the whole lifetime of the program.
3232
///
33-
/// # Note
33+
/// # Notes
3434
/// This macro is unsound on multi core systems.
3535
///
36+
/// For debuggability, you can set an explicit name for a singleton. This name only shows up the
37+
/// the debugger and is not referencable from other code. See example below.
38+
///
3639
/// # Example
3740
///
3841
/// ``` no_run
@@ -50,32 +53,40 @@ macro_rules! iprintln {
5053
/// fn alias() -> &'static mut bool {
5154
/// singleton!(: bool = false).unwrap()
5255
/// }
56+
///
57+
/// fn singleton_with_name() {
58+
/// // A name only for debugging purposes
59+
/// singleton!(FOO_BUFFER: [u8; 1024] = [0u8; 1024]);
60+
/// }
5361
/// ```
5462
#[macro_export]
5563
macro_rules! singleton {
56-
(: $ty:ty = $expr:expr) => {
64+
($name:ident: $ty:ty = $expr:expr) => {
5765
$crate::interrupt::free(|_| {
58-
static mut VAR: Option<$ty> = None;
66+
static mut $name: Option<$ty> = None;
5967

6068
#[allow(unsafe_code)]
61-
let used = unsafe { VAR.is_some() };
69+
let used = unsafe { $name.is_some() };
6270
if used {
6371
None
6472
} else {
6573
let expr = $expr;
6674

6775
#[allow(unsafe_code)]
6876
unsafe {
69-
VAR = Some(expr)
77+
$name = Some(expr)
7078
}
7179

7280
#[allow(unsafe_code)]
7381
unsafe {
74-
VAR.as_mut()
82+
$name.as_mut()
7583
}
7684
}
7785
})
7886
};
87+
(: $ty:ty = $expr:expr) => {
88+
$crate::singleton!(VAR: $ty = $expr)
89+
};
7990
}
8091

8192
/// ``` compile_fail

0 commit comments

Comments
 (0)