Skip to main content

stdiobus_core/
state.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026-present Raman Marozau <raman@worktif.com>
3// Copyright (c) 2026-present stdiobus contributors
4
5//! Bus state machine
6
7use std::fmt;
8
9/// State of the stdio_bus instance
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[repr(u8)]
12pub enum BusState {
13    /// Created but not started
14    Created = 0,
15    /// Workers being spawned
16    Starting = 1,
17    /// Running and accepting messages
18    Running = 2,
19    /// Graceful shutdown in progress
20    Stopping = 3,
21    /// Fully stopped
22    Stopped = 4,
23}
24
25impl BusState {
26    /// Check if the bus is in a state that accepts messages
27    pub fn accepts_messages(&self) -> bool {
28        matches!(self, Self::Running)
29    }
30
31    /// Check if the bus can be started
32    pub fn can_start(&self) -> bool {
33        matches!(self, Self::Created | Self::Stopped)
34    }
35
36    /// Check if the bus can be stopped
37    pub fn can_stop(&self) -> bool {
38        matches!(self, Self::Running | Self::Starting)
39    }
40}
41
42impl fmt::Display for BusState {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        match self {
45            Self::Created => write!(f, "CREATED"),
46            Self::Starting => write!(f, "STARTING"),
47            Self::Running => write!(f, "RUNNING"),
48            Self::Stopping => write!(f, "STOPPING"),
49            Self::Stopped => write!(f, "STOPPED"),
50        }
51    }
52}
53
54impl TryFrom<u8> for BusState {
55    type Error = ();
56
57    fn try_from(value: u8) -> Result<Self, Self::Error> {
58        match value {
59            0 => Ok(Self::Created),
60            1 => Ok(Self::Starting),
61            2 => Ok(Self::Running),
62            3 => Ok(Self::Stopping),
63            4 => Ok(Self::Stopped),
64            _ => Err(()),
65        }
66    }
67}