apparat/lib.rs
1//! # Apparat
2//!
3//! A lightweight, event-driven behavioral state machine
4//!
5//! Notable features:
6//!
7//! - No unsafe, unless you actively enable it (see "Feature flags" below)
8//! - No-std compatible
9//! - Small and fast to compile
10//! - Fewer than 250 lines of code
11//! - No dependencies
12//! - No procedural macros
13//! - Very ergonomic despite the manageable amount of macro magic
14//! - Highly flexible, suitable for many use cases
15//! - No dynamic dispatch, enables lots of compiler optimizations
16//!
17//! **Note:** I am still experimenting with this a bit so while it's below version 1.0, there might be breaking API changes in point releases. If you want to be sure, specify an exact version number in your Cargo.toml. In point-point-releases there won't be breaking changes ever.
18//!
19//! ## Feature flags
20//!
21//! ### "unsafe" (disabled by default)
22//!
23//! This feature flag facilitates more compiler optimizations in some cases (verified using *cargo asm*). This is achieved by using `core::hint::unreachable_unchecked()` in one place, where the author is certain enough that it's sound. Nevertheless, use this at your own risk. If you're curious, have a look at the code - I've written a safety-comment about my assumptions there. If you think I missed something, please file an issue.
24//!
25//! ## Architecture and usage
26//!
27//! ### Types you provide
28//!
29//! - An arbitrary number of types that represent the different states*
30//! - A context type that is mutably accessible while events are handled and during transitions.
31//! - An event type for the state machine to handle
32//! - An output type that is returned whenever an event is handled. If this is not needed, the unit type can be used.
33//!
34//! \* *The data within the state types is exclusively accessible in the respective state. It's getting dropped on transitions and moved when events are handled. These moves might get optimized out in some cases, but generally, if you want the best possible performance, the state types should be rather small and cheap to move.
35//! If it's impossible to keep them small and you are handling a lot of events without transitioning, consider putting the bigger data in a `Box` within the state type. Alternatively you could make that bigger data a part of the context type which won't get moved or dropped at all. But if you do the latter, the data will of course also be accessible from other states.*
36//!
37//! **Note:** All provided types must implement `Debug`.
38//!
39//! ### Entities that are generated
40//!
41//! - A wrapper enum with variants for all provided state types
42//! - An implementation of the `ApparatWrapper` trait for the wrapper enum
43//! - An implementation of the `ApparatState` trait for the wrapper enum. The enum delegates all method-calls of that trait to the inner state objects.
44//! - Implementations of the `Wrap` trait for all provided states (for convenience)
45//!
46//! ### Traits
47//!
48//! #### `ApparatState<StateWrapper>`
49//!
50//! This trait must be implemented for all state types. The only required method is `handle`, which takes an event and returns a `Handled<StateWrapper>`. That's just the next state wrapped in a `StateWrapper` alongside an output value. To construct this return type, we can first call `.wrap()` on our state and then `.with_output(...)` on the wrapper. If our output type implements `Default`, we can also use `.default_output()` instead.
51//!
52//! There are two other methods in the `ApparatState` trait: `init` and `is_init`. These form an initialization mechanism: After constructing an `Apparat` and after handling any event, `init` is called on the current state, until `is_init` returns `true`. This way, a single event can potentially trigger multiple, context dependent transitions. This happens in a while loop without any recursion. If a state doesn't need that, these methods can just be ignored.
53//!
54//! #### `TransitionFrom<OtherState, ContextData>`
55//!
56//! The `TransitionFrom` trait can be used to define specific transitions between states. The `TransitionTo` trait is then automatically implemented, so we can call `.transition` using the turbofish syntax. This design is similar to `From` and `Into` in the standard library, but `TransitionFrom` and `TransitionInto` can also mutate the provided context as a side effect. `TransitionInto` is recommended for trait bounds.
57//!
58//! If you have to define a lot of transitions using the same state constructor methods, you can use the `transitions` macro. Within the macro call, a single transition can be defined like this: `StateA -> StateB::new`. In this case, the type `StateB` would have to implement a method `new` with this signature: `fn new(prev: StateA, ctx: &mut ContextData) -> Self`. If transitions from multiple different states to `StateA` shall use the same transition method, the first argument has to be generic. All of this is demonstrated in the example called "counter_transitions_macro".
59//!
60//! #### `Wrap<StateWrapper>`
61//!
62//! The `Wrap<StateWrapper>` trait provides a `wrap` method to turn individual state objects into a `StateWrapper`. This is preferred over using `into` because it's more concise and enables type inference in more cases. `Wrap` is automatically implemented for all state types by the macro.
63//!
64//! ## Example
65//!
66//! For a slightly more complete example, have a look at *counter.rs* in the *examples* directory.
67//!
68//! ```rust
69//! //! This state machine switches from `StateA` to `StateB` on a single event but
70//! //! then needs three events to switch back to `StateA`. Additionally it keeps
71//! //! track of how often it got toggled back from `StateB` to `StateA`.
72//!
73//! use apparat::prelude::*;
74//!
75//! // Define the necessary types
76//! // --------------------------
77//!
78//! // States
79//!
80//! #[derive(Debug, Default)]
81//! pub struct StateA;
82//!
83//! #[derive(Debug, Default)]
84//! pub struct StateB {
85//! ignored_events: usize,
86//! }
87//!
88//! // Context
89//!
90//! // Data that survives state transitions and can be accessed in all states
91//! #[derive(Debug, Default)]
92//! pub struct ContextData {
93//! toggled: usize,
94//! }
95//!
96//! // Auto-generate the state wrapper and auto-implement traits
97//! // ---------------------------------------------------------
98//!
99//! // In this example we are just using the unit type for `event` and `output`
100//! // because we are only handling one kind of event and we don't care about values
101//! // being returned when events are handled.
102//! build_wrapper! {
103//! states: [StateA, StateB],
104//! wrapper: MyStateWrapper, // This is just an identifier we can pick
105//! context: ContextData,
106//! event: (),
107//! output: (),
108//! }
109//!
110//! // Define transitions
111//! // ------------------
112//!
113//! impl TransitionFrom<StateB> for StateA {
114//! fn transition_from(_prev: StateB, ctx: &mut ContextData) -> Self {
115//! // Increase toggled value
116//! ctx.toggled += 1;
117//! println!("B -> A | toggled: {}", ctx.toggled);
118//! StateA::default()
119//! }
120//! }
121//!
122//! impl TransitionFrom<StateA> for StateB {
123//! fn transition_from(_prev: StateA, ctx: &mut ContextData) -> Self {
124//! println!("A -> B | toggled: {}", ctx.toggled);
125//! StateB::default()
126//! }
127//! }
128//!
129//! // Implement the `ApparatState` trait for all states
130//! // -------------------------------------------------
131//!
132//! impl ApparatState for StateA {
133//! type Wrapper = MyStateWrapper;
134//!
135//! fn handle(self, _event: (), ctx: &mut ContextData) -> Handled<MyStateWrapper> {
136//! println!("A handles event | toggled: {}", ctx.toggled);
137//! // Transition to `StateB`
138//! let state_b = self.transition::<StateB>(ctx);
139//! // Now we need to wrap that `state_b` in a `MyStateWrapper`...
140//! let state_b_wrapped = state_b.wrap();
141//! // ... and add an output value to turn it into a `Handled<...>`.
142//! state_b_wrapped.default_output()
143//! // If we would need a different output value or our output type wouldn't
144//! // implement `Default` we would have to use `.with_output(...)` instead.
145//! }
146//! }
147//!
148//! impl ApparatState for StateB {
149//! type Wrapper = MyStateWrapper;
150//!
151//! fn handle(mut self, _event: (), ctx: &mut ContextData) -> Handled<MyStateWrapper> {
152//! println!("B handles event | toggled: {}", ctx.toggled);
153//! if self.ignored_events == 2 {
154//! self.transition::<StateA>(ctx).wrap().default_output()
155//! } else {
156//! self.ignored_events += 1;
157//! self.wrap().default_output()
158//! }
159//! }
160//! }
161//!
162//! // Run the machine
163//! // ---------------
164//!
165//! fn main() {
166//! let mut apparat = Apparat::new(StateA::default().wrap(), ContextData::default());
167//!
168//! // Handle some events
169//! for _ in 0..10 {
170//! apparat.handle(());
171//! }
172//! }
173//! ```
174
175#![no_std]
176#![warn(clippy::pedantic)]
177#![allow(clippy::inline_always, clippy::needless_doctest_main)]
178
179pub mod prelude {
180 pub use crate::{
181 build_wrapper, transitions, Apparat, ApparatState, ApparatTrait, ApparatWrapper,
182 ApparatWrapperDefaultOutput, Handled, TransitionFrom, TransitionTo, Wrap,
183 };
184}
185
186/// This trait is used to associate all the types used together in an `Apparat`
187/// with the state wrapper enum, so users of the library dont' need to specify
188/// all these types every time they implement the `ApparatState` trait for one
189/// of their state types.
190pub trait ApparatWrapper: Sized {
191 type Context;
192 type Event;
193 type Output;
194
195 fn with_output(self, output: Self::Output) -> Handled<Self> {
196 Handled::new(self, output)
197 }
198}
199
200pub trait ApparatWrapperDefaultOutput: ApparatWrapper {
201 fn default_output(self) -> Handled<Self>;
202}
203
204impl<Wrapper: ApparatWrapper> ApparatWrapperDefaultOutput for Wrapper
205where
206 Wrapper::Output: Default,
207{
208 #[inline]
209 fn default_output(self) -> Handled<Self> {
210 self.into()
211 }
212}
213
214pub trait ApparatTrait<Wrapper>
215where
216 Wrapper: ApparatWrapper + ApparatState<Wrapper = Wrapper>,
217{
218 fn new(state: Wrapper, ctx: Wrapper::Context) -> Self;
219 fn handle(&mut self, event: Wrapper::Event) -> Wrapper::Output;
220}
221
222/// The actual state machine that handles your events and manages their
223/// initialization and transitions
224#[derive(Debug)]
225pub struct Apparat<Wrapper: ApparatWrapper> {
226 state: Option<Wrapper>,
227 ctx: Wrapper::Context,
228}
229
230impl<Wrapper> ApparatTrait<Wrapper> for Apparat<Wrapper>
231where
232 Wrapper: ApparatWrapper + ApparatState<Wrapper = Wrapper>,
233{
234 fn new(mut state: Wrapper, mut ctx: Wrapper::Context) -> Self {
235 while !state.is_init(&ctx) {
236 state = state.init(&mut ctx);
237 }
238 Self {
239 state: Some(state),
240 ctx,
241 }
242 }
243
244 #[inline]
245 fn handle(&mut self, event: Wrapper::Event) -> Wrapper::Output {
246 #[cfg(feature = "unsafe")]
247 // Safety: `self.state` can't be accessed directly from outside of this
248 // module. The only methods accessing it are this one and `new`. Both
249 // ultimately leave a `Some` value in `self.state`. Panicking while it's
250 // `None` would only lead to undefined behavior if there would be an
251 // unsafe `Drop` implementation for `Apparat` that assumes that it's
252 // `Some`, which isn't the case. Since this method takes `&mut self`
253 // there also can't be an overlapping call from a different thread
254 // thanks to the almighty borrow checker <3.
255 let state = self
256 .state
257 .take()
258 .unwrap_or_else(|| unsafe { core::hint::unreachable_unchecked() });
259
260 #[cfg(not(feature = "unsafe"))]
261 // The performance impact is negligible in most cases, but using this
262 // "safe" version does sometimes lead to slightly less optimized code.
263 let state = self.state.take().expect("https://xkcd.com/2200/");
264
265 let mut handled = state.handle(event, &mut self.ctx);
266 while !handled.state.is_init(&self.ctx) {
267 handled.state = handled.state.init(&mut self.ctx);
268 }
269 self.state = Some(handled.state);
270 handled.result
271 }
272}
273
274/// A trait that must be implemented by all provided state types. Have a look at
275/// the readme or the examples for details.
276pub trait ApparatState: Sized {
277 type Wrapper: ApparatWrapper + From<Self>;
278
279 #[inline(always)]
280 fn init(
281 self,
282 _ctx: &mut <<Self as ApparatState>::Wrapper as ApparatWrapper>::Context,
283 ) -> Self::Wrapper {
284 Self::Wrapper::from(self)
285 }
286
287 fn handle(
288 self,
289 _event: <<Self as ApparatState>::Wrapper as ApparatWrapper>::Event,
290 _ctx: &mut <<Self as ApparatState>::Wrapper as ApparatWrapper>::Context,
291 ) -> Handled<<Self as ApparatState>::Wrapper>;
292
293 #[inline(always)]
294 fn is_init(&self, _ctx: &<<Self as ApparatState>::Wrapper as ApparatWrapper>::Context) -> bool {
295 true
296 }
297}
298
299/// This type is being returned whenever an event is handled by a state type. It
300/// contains the new state alongside an output value that will be returned to
301/// the caller of the `handle` method.
302#[derive(Debug)]
303pub struct Handled<Wrapper: ApparatWrapper> {
304 pub state: Wrapper,
305 pub result: Wrapper::Output,
306}
307
308impl<Wrapper: ApparatWrapper> Handled<Wrapper> {
309 #[inline]
310 pub fn new(state: Wrapper, result: Wrapper::Output) -> Self {
311 Self { state, result }
312 }
313}
314
315impl<Wrapper> Handled<Wrapper>
316where
317 Wrapper: ApparatWrapper,
318 Wrapper::Output: Default,
319{
320 #[inline]
321 pub fn new_default(state: Wrapper) -> Self {
322 Self {
323 state,
324 result: Wrapper::Output::default(),
325 }
326 }
327}
328
329impl<Wrapper> From<Wrapper> for Handled<Wrapper>
330where
331 Wrapper: ApparatWrapper,
332 Wrapper::Output: Default,
333{
334 #[inline(always)]
335 fn from(wrapper: Wrapper) -> Self {
336 Self::new_default(wrapper)
337 }
338}
339
340/// Define transitions between states. These transition functions can access the
341/// shared context/data mutably.
342pub trait TransitionFrom<FromState: ApparatState> {
343 fn transition_from(
344 prev: FromState,
345 _ctx: &mut <<FromState as ApparatState>::Wrapper as ApparatWrapper>::Context,
346 ) -> Self;
347}
348
349/// Similar to `Into` in std, this is mostly for convenience and should not get
350/// implemented manually. Implement `TransitionFrom` instead and use
351/// `TransitionInto` in trait bounds, when needed.
352pub trait TransitionTo<Context>: Sized + ApparatState {
353 #[inline(always)]
354 fn transition<Next>(
355 self,
356 ctx: &mut <<Self as ApparatState>::Wrapper as ApparatWrapper>::Context,
357 ) -> Next
358 where
359 Next: ApparatState<Wrapper = Self::Wrapper> + TransitionFrom<Self>,
360 {
361 Next::transition_from(self, ctx)
362 }
363}
364
365// Blanket implementation so state types can transition into themselves
366impl<T: ApparatState> TransitionTo<T> for T {}
367
368/// An alternative to `std::Into` for turning state types into the respective
369/// state wrapper enum. This is preferred over `Into` because it provides more
370/// reliable type inference in the context of apparat.
371pub trait Wrap<Wrapper> {
372 fn wrap(self) -> Wrapper;
373}
374
375/// Generate an enum that wraps all provided state types. Additionally all
376/// necessary traits are implemented for it, so the wrapper can be used within
377/// an `Apparat` state machine.
378#[macro_export]
379macro_rules! build_wrapper {
380 (
381 states: [$state1:ident, $($state:ident),* $(,)*],
382 wrapper: $wrapper:ident,
383 context: $context:ty,
384 event: $event:ty,
385 output: $output:ty
386 $(,)*
387 ) => {
388 #[derive(Debug)]
389 pub enum $wrapper {
390 $state1($state1),
391 $(
392 $state($state)
393 ),*
394 }
395
396 impl ::apparat::ApparatWrapper for $wrapper {
397 type Context = $context;
398 type Event = $event;
399 type Output = $output;
400 }
401
402 impl ::apparat::ApparatState for $wrapper {
403 type Wrapper = Self;
404
405 #[inline]
406 fn init(self, ctx: &mut $context) -> Self {
407 match self {
408 $wrapper::$state1(state) => state.init(ctx),
409 $(
410 $wrapper::$state(state) => state.init(ctx)
411 ),*
412 }
413 }
414
415 #[inline]
416 fn handle(self, event: $event, ctx: &mut $context) -> Handled<$wrapper> {
417 match self {
418 $wrapper::$state1(state) => state.handle(event, ctx),
419 $(
420 $wrapper::$state(state) => state.handle(event, ctx)
421 ),*
422 }
423 }
424
425 #[inline]
426 fn is_init(&self, ctx: &$context) -> bool {
427 match self {
428 $wrapper::$state1(state) => state.is_init(ctx),
429 $(
430 $wrapper::$state(state) => state.is_init(ctx)
431 ),*
432 }
433 }
434 }
435
436 impl ::std::convert::From<$state1> for $wrapper {
437 #[inline(always)]
438 fn from(state: $state1) -> $wrapper {
439 $wrapper::$state1(state)
440 }
441 }
442
443 // These manual implementations are needed (instead of a blanket impl) so
444 // the wrapper type can get inferred when wrap is called on a state
445 // object.
446 impl ::apparat::Wrap<$wrapper> for $state1 {
447 #[inline(always)]
448 fn wrap(self) -> $wrapper {
449 $wrapper::$state1(self)
450 }
451 }
452
453 $(
454 impl ::std::convert::From<$state> for $wrapper {
455 #[inline(always)]
456 fn from(state: $state) -> $wrapper {
457 $wrapper::$state(state)
458 }
459 }
460
461 impl ::apparat::Wrap<$wrapper> for $state {
462 #[inline(always)]
463 fn wrap(self) -> $wrapper {
464 $wrapper::$state(self)
465 }
466 }
467 )*
468 };
469}
470
471/// Short hand for implementing the `TransitionFrom` trait for multiple state
472/// types, defining multiple transitions. This trait can easily be implemented
473/// manually too, so this macro is just an optional tool for convenience. Find a
474/// usage demo in the example "counter_transitions_macro".
475#[macro_export]
476macro_rules! transitions {
477 ($($state_a:ident -> $state_b:ident :: $function:ident),* $(,)*) => {
478 $(
479 impl TransitionFrom<$state_a> for $state_b {
480 fn transition_from(
481 prev: $state_a,
482 ctx: &mut <<$state_a as ApparatState>::Wrapper as ApparatWrapper>::Context
483 ) -> Self {
484 $state_b::$function(prev, ctx)
485 }
486 }
487 )*
488 };
489}