embassy/embassy-hal-common/src/macros.rs

97 lines
2.6 KiB
Rust
Raw Normal View History

#[macro_export]
macro_rules! peripherals {
2021-03-27 03:12:58 +01:00
($($(#[$cfg:meta])? $name:ident),*$(,)?) => {
2021-03-21 21:58:59 +01:00
pub mod peripherals {
$(
$(#[$cfg])?
#[allow(non_camel_case_types)]
2021-03-27 03:12:58 +01:00
pub struct $name { _private: () }
2021-03-21 21:58:59 +01:00
$(#[$cfg])?
impl $name {
/// Unsafely create an instance of this peripheral out of thin air.
///
/// # Safety
///
/// You must ensure that you're only using one instance of this type at a time.
2021-03-21 21:58:59 +01:00
#[inline]
pub unsafe fn steal() -> Self {
2021-03-21 21:58:59 +01:00
Self{ _private: ()}
}
}
2021-03-21 21:58:59 +01:00
$(#[$cfg])?
$crate::unsafe_impl_unborrow!($name);
2021-03-21 21:58:59 +01:00
)*
}
2021-03-27 03:12:58 +01:00
#[allow(non_snake_case)]
pub struct Peripherals {
$(
$(#[$cfg])?
2021-03-27 03:12:58 +01:00
pub $name: peripherals::$name,
)*
}
impl Peripherals {
2021-03-21 21:58:59 +01:00
///Returns all the peripherals *once*
#[inline]
pub(crate) fn take() -> Self {
2021-03-21 21:58:59 +01:00
#[no_mangle]
static mut _EMBASSY_DEVICE_PERIPHERALS: bool = false;
critical_section::with(|_| unsafe {
if _EMBASSY_DEVICE_PERIPHERALS {
panic!("init called more than once!")
2021-03-21 21:58:59 +01:00
}
_EMBASSY_DEVICE_PERIPHERALS = true;
Self::steal()
2021-03-21 21:58:59 +01:00
})
}
}
impl Peripherals {
/// Unsafely create an instance of this peripheral out of thin air.
///
/// # Safety
///
/// You must ensure that you're only using one instance of this type at a time.
2021-03-21 21:58:59 +01:00
#[inline]
pub unsafe fn steal() -> Self {
Self {
$(
$(#[$cfg])?
$name: peripherals::$name::steal(),
)*
}
}
}
};
}
2021-03-21 22:09:06 +01:00
#[macro_export]
macro_rules! unborrow {
($($name:ident),*) => {
$(
2022-07-03 23:16:10 +02:00
let mut $name = $name.unborrow();
2021-03-21 22:09:06 +01:00
)*
}
}
2021-03-27 03:33:32 +01:00
#[macro_export]
2021-05-19 23:21:31 +02:00
macro_rules! unsafe_impl_unborrow {
2021-03-27 03:33:32 +01:00
($type:ident) => {
unsafe impl $crate::Unborrow for $type {
2021-03-27 03:33:32 +01:00
type Target = $type;
#[inline]
2022-07-03 23:16:10 +02:00
fn unborrow<'a>(self) -> $crate::Unborrowed<'a, Self::Target>
where
Self: 'a,
{
$crate::Unborrowed::new(self)
2021-03-27 03:33:32 +01:00
}
}
};
}