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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
//! # Apparat //! //! A lightweight, event-driven behavioral state machine //! //! Notable features: //! //! - No unsafe, unless you actively enable it (see "Feature flags" below) //! - No-std compatible //! - Small and fast to compile //! - Fewer than 250 lines of code //! - No dependencies //! - No procedural macros //! - Very ergonomic despite the manageable amount of macro magic //! - Highly flexible, suitable for many use cases //! - No dynamic dispatch, enables lots of compiler optimizations //! //! **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. //! //! ## Feature flags //! //! ### "unsafe" (disabled by default) //! //! 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. //! //! ## Architecture and usage //! //! ### Types you provide //! //! - An arbitrary number of types that represent the different states* //! - A context type that is mutably accessible while events are handled and during transitions. //! - An event type for the state machine to handle //! - An output type that is returned whenever an event is handled. If this is not needed, the unit type can be used. //! //! \* *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. //! 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.* //! //! **Note:** All provided types must implement `Debug`. //! //! ### Entities that are generated //! //! - A wrapper enum with variants for all provided state types //! - An implementation of the `ApparatWrapper` trait for the wrapper enum //! - An implementation of the `ApparatState` trait for the wrapper enum. The enum delegates all method-calls of that trait to the inner state objects. //! - Implementations of the `Wrap` trait for all provided states (for convenience) //! //! ### Traits //! //! #### `ApparatState<StateWrapper>` //! //! 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. //! //! 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. //! //! #### `TransitionFrom<OtherState, ContextData>` //! //! 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. //! //! 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". //! //! #### `Wrap<StateWrapper>` //! //! 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. //! //! ## Example //! //! For a slightly more complete example, have a look at *counter.rs* in the *examples* directory. //! //! ```rust //! //! This state machine switches from `StateA` to `StateB` on a single event but //! //! then needs three events to switch back to `StateA`. Additionally it keeps //! //! track of how often it got toggled back from `StateB` to `StateA`. //! //! use apparat::prelude::*; //! //! // Define the necessary types //! // -------------------------- //! //! // States //! //! #[derive(Debug, Default)] //! pub struct StateA; //! //! #[derive(Debug, Default)] //! pub struct StateB { //! ignored_events: usize, //! } //! //! // Context //! //! // Data that survives state transitions and can be accessed in all states //! #[derive(Debug, Default)] //! pub struct ContextData { //! toggled: usize, //! } //! //! // Auto-generate the state wrapper and auto-implement traits //! // --------------------------------------------------------- //! //! // In this example we are just using the unit type for `event` and `output` //! // because we are only handling one kind of event and we don't care about values //! // being returned when events are handled. //! build_wrapper! { //! states: [StateA, StateB], //! wrapper: MyStateWrapper, // This is just an identifier we can pick //! context: ContextData, //! event: (), //! output: (), //! } //! //! // Define transitions //! // ------------------ //! //! impl TransitionFrom<StateB> for StateA { //! fn transition_from(_prev: StateB, ctx: &mut ContextData) -> Self { //! // Increase toggled value //! ctx.toggled += 1; //! println!("B -> A | toggled: {}", ctx.toggled); //! StateA::default() //! } //! } //! //! impl TransitionFrom<StateA> for StateB { //! fn transition_from(_prev: StateA, ctx: &mut ContextData) -> Self { //! println!("A -> B | toggled: {}", ctx.toggled); //! StateB::default() //! } //! } //! //! // Implement the `ApparatState` trait for all states //! // ------------------------------------------------- //! //! impl ApparatState for StateA { //! type Wrapper = MyStateWrapper; //! //! fn handle(self, _event: (), ctx: &mut ContextData) -> Handled<MyStateWrapper> { //! println!("A handles event | toggled: {}", ctx.toggled); //! // Transition to `StateB` //! let state_b = self.transition::<StateB>(ctx); //! // Now we need to wrap that `state_b` in a `MyStateWrapper`... //! let state_b_wrapped = state_b.wrap(); //! // ... and add an output value to turn it into a `Handled<...>`. //! state_b_wrapped.default_output() //! // If we would need a different output value or our output type wouldn't //! // implement `Default` we would have to use `.with_output(...)` instead. //! } //! } //! //! impl ApparatState for StateB { //! type Wrapper = MyStateWrapper; //! //! fn handle(mut self, _event: (), ctx: &mut ContextData) -> Handled<MyStateWrapper> { //! println!("B handles event | toggled: {}", ctx.toggled); //! if self.ignored_events == 2 { //! self.transition::<StateA>(ctx).wrap().default_output() //! } else { //! self.ignored_events += 1; //! self.wrap().default_output() //! } //! } //! } //! //! // Run the machine //! // --------------- //! //! fn main() { //! let mut apparat = Apparat::new(StateA::default().wrap(), ContextData::default()); //! //! // Handle some events //! for _ in 0..10 { //! apparat.handle(()); //! } //! } //! ``` #![no_std] #![warn(clippy::pedantic)] #![allow(clippy::inline_always, clippy::needless_doctest_main)] pub mod prelude { pub use crate::{ build_wrapper, transitions, Apparat, ApparatState, ApparatTrait, ApparatWrapper, ApparatWrapperDefaultOutput, Handled, TransitionFrom, TransitionTo, Wrap, }; } /// This trait is used to associate all the types used together in an `Apparat` /// with the state wrapper enum, so users of the library dont' need to specify /// all these types every time they implement the `ApparatState` trait for one /// of their state types. pub trait ApparatWrapper: Sized { type Context; type Event; type Output; fn with_output(self, output: Self::Output) -> Handled<Self> { Handled::new(self, output) } } pub trait ApparatWrapperDefaultOutput: ApparatWrapper { fn default_output(self) -> Handled<Self>; } impl<Wrapper: ApparatWrapper> ApparatWrapperDefaultOutput for Wrapper where Wrapper::Output: Default, { #[inline] fn default_output(self) -> Handled<Self> { self.into() } } pub trait ApparatTrait<Wrapper> where Wrapper: ApparatWrapper + ApparatState<Wrapper = Wrapper>, { fn new(state: Wrapper, ctx: Wrapper::Context) -> Self; fn handle(&mut self, event: Wrapper::Event) -> Wrapper::Output; } /// The actual state machine that handles your events and manages their /// initialization and transitions #[derive(Debug)] pub struct Apparat<Wrapper: ApparatWrapper> { state: Option<Wrapper>, ctx: Wrapper::Context, } impl<Wrapper> ApparatTrait<Wrapper> for Apparat<Wrapper> where Wrapper: ApparatWrapper + ApparatState<Wrapper = Wrapper>, { fn new(mut state: Wrapper, mut ctx: Wrapper::Context) -> Self { while !state.is_init(&ctx) { state = state.init(&mut ctx); } Self { state: Some(state), ctx, } } #[inline] fn handle(&mut self, event: Wrapper::Event) -> Wrapper::Output { #[cfg(feature = "unsafe")] // Safety: `self.state` can't be accessed directly from outside of this // module. The only methods accessing it are this one and `new`. Both // ultimately leave a `Some` value in `self.state`. Panicking while it's // `None` would only lead to undefined behavior if there would be an // unsafe `Drop` implementation for `Apparat` that assumes that it's // `Some`, which isn't the case. Since this method takes `&mut self` // there also can't be an overlapping call from a different thread // thanks to the almighty borrow checker <3. let state = self .state .take() .unwrap_or_else(|| unsafe { core::hint::unreachable_unchecked() }); #[cfg(not(feature = "unsafe"))] // The performance impact is negligible in most cases, but using this // "safe" version does sometimes lead to slightly less optimized code. let state = self.state.take().expect("https://xkcd.com/2200/"); let mut handled = state.handle(event, &mut self.ctx); while !handled.state.is_init(&self.ctx) { handled.state = handled.state.init(&mut self.ctx); } self.state = Some(handled.state); handled.result } } /// A trait that must be implemented by all provided state types. Have a look at /// the readme or the examples for details. pub trait ApparatState: Sized { type Wrapper: ApparatWrapper + From<Self>; #[inline(always)] fn init( self, _ctx: &mut <<Self as ApparatState>::Wrapper as ApparatWrapper>::Context, ) -> Self::Wrapper { Self::Wrapper::from(self) } fn handle( self, _event: <<Self as ApparatState>::Wrapper as ApparatWrapper>::Event, _ctx: &mut <<Self as ApparatState>::Wrapper as ApparatWrapper>::Context, ) -> Handled<<Self as ApparatState>::Wrapper>; #[inline(always)] fn is_init(&self, _ctx: &<<Self as ApparatState>::Wrapper as ApparatWrapper>::Context) -> bool { true } } /// This type is being returned whenever an event is handled by a state type. It /// contains the new state alongside an output value that will be returned to /// the caller of the `handle` method. #[derive(Debug)] pub struct Handled<Wrapper: ApparatWrapper> { pub state: Wrapper, pub result: Wrapper::Output, } impl<Wrapper: ApparatWrapper> Handled<Wrapper> { #[inline] pub fn new(state: Wrapper, result: Wrapper::Output) -> Self { Self { state, result } } } impl<Wrapper> Handled<Wrapper> where Wrapper: ApparatWrapper, Wrapper::Output: Default, { #[inline] pub fn new_default(state: Wrapper) -> Self { Self { state, result: Wrapper::Output::default(), } } } impl<Wrapper> From<Wrapper> for Handled<Wrapper> where Wrapper: ApparatWrapper, Wrapper::Output: Default, { #[inline(always)] fn from(wrapper: Wrapper) -> Self { Self::new_default(wrapper) } } /// Define transitions between states. These transition functions can access the /// shared context/data mutably. pub trait TransitionFrom<FromState: ApparatState> { fn transition_from( prev: FromState, _ctx: &mut <<FromState as ApparatState>::Wrapper as ApparatWrapper>::Context, ) -> Self; } /// Similar to `Into` in std, this is mostly for convenience and should not get /// implemented manually. Implement `TransitionFrom` instead and use /// `TransitionInto` in trait bounds, when needed. pub trait TransitionTo<Context>: Sized + ApparatState { #[inline(always)] fn transition<Next>( self, ctx: &mut <<Self as ApparatState>::Wrapper as ApparatWrapper>::Context, ) -> Next where Next: ApparatState<Wrapper = Self::Wrapper> + TransitionFrom<Self>, { Next::transition_from(self, ctx) } } // Blanket implementation so state types can transition into themselves impl<T: ApparatState> TransitionTo<T> for T {} /// An alternative to `std::Into` for turning state types into the respective /// state wrapper enum. This is preferred over `Into` because it provides more /// reliable type inference in the context of apparat. pub trait Wrap<Wrapper> { fn wrap(self) -> Wrapper; } /// Generate an enum that wraps all provided state types. Additionally all /// necessary traits are implemented for it, so the wrapper can be used within /// an `Apparat` state machine. #[macro_export] macro_rules! build_wrapper { ( states: [$state1:ident, $($state:ident),* $(,)*], wrapper: $wrapper:ident, context: $context:ty, event: $event:ty, output: $output:ty $(,)* ) => { #[derive(Debug)] pub enum $wrapper { $state1($state1), $( $state($state) ),* } impl ::apparat::ApparatWrapper for $wrapper { type Context = $context; type Event = $event; type Output = $output; } impl ::apparat::ApparatState for $wrapper { type Wrapper = Self; #[inline] fn init(self, ctx: &mut $context) -> Self { match self { $wrapper::$state1(state) => state.init(ctx), $( $wrapper::$state(state) => state.init(ctx) ),* } } #[inline] fn handle(self, event: $event, ctx: &mut $context) -> Handled<$wrapper> { match self { $wrapper::$state1(state) => state.handle(event, ctx), $( $wrapper::$state(state) => state.handle(event, ctx) ),* } } #[inline] fn is_init(&self, ctx: &$context) -> bool { match self { $wrapper::$state1(state) => state.is_init(ctx), $( $wrapper::$state(state) => state.is_init(ctx) ),* } } } impl ::std::convert::From<$state1> for $wrapper { #[inline(always)] fn from(state: $state1) -> $wrapper { $wrapper::$state1(state) } } // These manual implementations are needed (instead of a blanket impl) so // the wrapper type can get inferred when wrap is called on a state // object. impl ::apparat::Wrap<$wrapper> for $state1 { #[inline(always)] fn wrap(self) -> $wrapper { $wrapper::$state1(self) } } $( impl ::std::convert::From<$state> for $wrapper { #[inline(always)] fn from(state: $state) -> $wrapper { $wrapper::$state(state) } } impl ::apparat::Wrap<$wrapper> for $state { #[inline(always)] fn wrap(self) -> $wrapper { $wrapper::$state(self) } } )* }; } /// Short hand for implementing the `TransitionFrom` trait for multiple state /// types, defining multiple transitions. This trait can easily be implemented /// manually too, so this macro is just an optional tool for convenience. Find a /// usage demo in the example "counter_transitions_macro". #[macro_export] macro_rules! transitions { ($($state_a:ident -> $state_b:ident :: $function:ident),* $(,)*) => { $( impl TransitionFrom<$state_a> for $state_b { fn transition_from( prev: $state_a, ctx: &mut <<$state_a as ApparatState>::Wrapper as ApparatWrapper>::Context ) -> Self { $state_b::$function(prev, ctx) } } )* }; }