Re: [RFC PATCH 1/2] rust: LED abstraction

From: Marek Behún
Date: Sat Nov 16 2024 - 10:47:56 EST


On Wed, Oct 09, 2024 at 12:57:58PM +0200, Fiona Behrens wrote:

> +/// Color of an LED.
> +#[derive(Copy, Clone)]
> +pub enum Color {
> + /// White
> + White,
> + /// Red
> + Red,
> + /// Green
> + Green,
> + /// Blue
> + Blue,
> + /// Amber
> + Amber,
> + /// Violet
> + Violet,
> + /// Yellow
> + Yellow,
> + /// Purple
> + Purple,
> + /// Orange
> + Orange,
> + /// Pink
> + Pink,
> + /// Cyan
> + Cyan,
> + /// Lime
> + Lime,

Why these repetitions?

> +impl TryFrom<u32> for Color {
> + type Error = Error;
> +
> + fn try_from(value: u32) -> Result<Self, Self::Error> {
> + Ok(match value {
> + bindings::LED_COLOR_ID_WHITE => Color::White,
> + bindings::LED_COLOR_ID_RED => Color::Red,
> + bindings::LED_COLOR_ID_GREEN => Color::Green,
> + bindings::LED_COLOR_ID_BLUE => Color::Blue,
> + bindings::LED_COLOR_ID_AMBER => Color::Amber,
> + bindings::LED_COLOR_ID_VIOLET => Color::Violet,
> + bindings::LED_COLOR_ID_YELLOW => Color::Yellow,
> + bindings::LED_COLOR_ID_PURPLE => Color::Purple,
> + bindings::LED_COLOR_ID_ORANGE => Color::Orange,
> + bindings::LED_COLOR_ID_PINK => Color::Pink,
> + bindings::LED_COLOR_ID_CYAN => Color::Cyan,
> + bindings::LED_COLOR_ID_LIME => Color::Lime,
> + bindings::LED_COLOR_ID_IR => Color::IR,
> + bindings::LED_COLOR_ID_MULTI => Color::Multi,
> + bindings::LED_COLOR_ID_RGB => Color::RGB,
> + _ => return Err(EINVAL),
> + })
> + }
> +}

How does Rust compile these? If these constants compile to the same
numeric values, i.e. if
LED_COLOR_ID_AMBER == Color::Amber,
will the compiler compile away the function?

How do enums work in Rust?

> +impl<'a, T> Led<T>

offtopic, what is 'a ? What does the ' mean? Is impl<> something like
template in c++?

> +where
> + T: Operations + 'a,

What does + mean here?

> +/// LED brightness.
> +#[derive(Debug, Copy, Clone)]
> +pub enum Brightness {
> + /// LED off.
> + Off,
> + /// Led set to the given value.
> + On(NonZeroU8),
> +}
> +
> +impl Brightness {
> + /// Half LED brightness
> + // SAFETY: constant value non zero
> + pub const HALF: Self = Self::On(unsafe { NonZeroU8::new_unchecked(127) });
> + /// Full LED brightness.
> + pub const FULL: Self = Self::On(NonZeroU8::MAX);

These LED_OFF, LED_ON, LED_HALF and LED_FULL are deprecated constants
that should not be used anymore. enum led_brightness will be either
uint8_t or usigned int in the future.

Is it possible to not infect Rust with these deprecated constants?

Marek