1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use anyhow::Result;

/// A trait representing a poller that performs periodic tasks.
///
/// # Errors
/// This trait's `poll` method returns an error if the polling operation fails.
pub trait Poller {
    /// Polls for periodic tasks.
    ///
    /// # Errors
    /// Returns an error if the polling operation fails.
    fn poll(&mut self) -> Result<!>;
}

/// Represents an on/off state, optionally carrying additional data when on.
///
/// # Type Parameters
/// * `T` - The type of additional data carried when in the `On` state. Defaults to `()`.
///
/// # Variants
/// * `Off` - The switch is turned off.
/// * `On(Option<T>)` - The switch is on, optionally with additional data.
pub enum State<T = ()> {
    Off,
    On(Option<T>),
}

impl<T> State<T> {
    /// Creates a new `State` in the `On` position with no additional data.
    ///
    /// # Returns
    /// A `State` in the `On` position with `None` data.
    pub const fn on() -> Self {
        State::On(None)
    }

    /// Creates a new `State` in the `Off` position.
    ///
    /// # Returns
    /// A `State` in the `Off` position.
    #[must_use]
    pub const fn off() -> Self {
        State::Off
    }

    /// Returns `true` if the state is `Off`.
    ///
    /// # Returns
    /// `true` if `Off`, `false` otherwise.
    pub fn is_off(&self) -> bool {
        matches!(self, State::Off)
    }

    /// Returns `true` if the state is `On`.
    ///
    /// # Returns
    /// `true` if `On`, `false` otherwise.
    pub fn is_on(&self) -> bool {
        matches!(self, State::On(_))
    }

    /// Toggles between `On` and `Off`, clearing any additional data.
    pub fn toggle(&mut self) {
        *self = match self {
            State::On(_) => State::Off,
            State::Off => State::On(None),
        };
    }
}

/// A trait representing a switch that can toggle its state.
///
/// # Errors
/// This trait's `toggle` method returns an error if the toggle operation fails.
pub trait Switch {
    /// Toggles the state of the switch.
    ///
    /// # Returns
    /// `Ok(())` on success.
    ///
    /// # Errors
    /// Returns an error if the toggle operation fails.
    fn toggle(&mut self) -> Result<()>;
}