Skip to content

Commit

Permalink
LED: Add fallible initialization, deprecate new for new_unchecked
Browse files Browse the repository at this point in the history
  • Loading branch information
chrysn committed Aug 24, 2024
1 parent 294d122 commit 24105fe
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/led.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,54 @@ use core::convert::Infallible;
/// LEDs are accessible safely; any not implemented on a board are silently ignored.
pub struct LED<const I: u8>(());

/// The indicated LED is not present on the current board.
#[derive(Debug)]
pub struct LedNotPresent;

impl<const I: u8> LED<I> {
#[deprecated(
note = "Use new_unchecked() to retain the behavior this function has always had; future versions of `.new()` will panic when used with a board that does not have that LED.",
since = "0.9.1"
)]
pub const fn new() -> Self {
Self::new_unchecked()
}

/// Accesses the LED numbered `I`.
///
/// It is not an error if this board does not have a LED with that number; the resulting struct
/// will be available but its methods have no effect.
pub const fn new_unchecked() -> Self {
assert!(I < 8, "RIOT only defines LED0..7");
Self(())
}

/// Accesses the LED numbered `I`.
///
/// An LED is returned if present on the board, which is known at build time.
pub const fn new_checked() -> Result<Self, LedNotPresent> {
if Self::is_present() {
Ok(Self(()))
} else {
Err(LedNotPresent)
}
}

const fn is_present() -> bool {
unsafe {
match I {
0 => riot_sys::macro_LED0_IS_PRESENT() != -1,
1 => riot_sys::macro_LED1_IS_PRESENT() != -1,
2 => riot_sys::macro_LED2_IS_PRESENT() != -1,
3 => riot_sys::macro_LED3_IS_PRESENT() != -1,
4 => riot_sys::macro_LED4_IS_PRESENT() != -1,
5 => riot_sys::macro_LED5_IS_PRESENT() != -1,
6 => riot_sys::macro_LED6_IS_PRESENT() != -1,
7 => riot_sys::macro_LED7_IS_PRESENT() != -1,
_ => panic!("RIOT only defines LED0..7"),
}
}
}
}

impl<const I: u8> switch_hal::OutputSwitch for LED<I> {
Expand Down

0 comments on commit 24105fe

Please sign in to comment.