statig 0.4.1

Hierarchical state machines for designing event-driven systems
Documentation
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
use core::fmt::Debug;

use crate::awaitable::{Inner, IntoStateMachine, State, Superstate};

/// A state machine where the shared storage is of type `Self`.
pub trait IntoStateMachineExt: IntoStateMachine
where
    for<'sub> Self::Superstate<'sub>: Superstate<Self>,
    Self::State: State<Self>,
{
    /// Create a state machine that will be lazily initialized.
    fn state_machine(self) -> StateMachine<Self>
    where
        Self: Sized,
    {
        let inner = Inner {
            shared_storage: self,
            state: Self::initial(),
        };
        StateMachine {
            inner,
            initialized: false,
        }
    }

    /// Create an uninitialized state machine that must be explicitly initialized with
    /// [`init`](UninitializedStateMachine::init).
    fn uninitialized_state_machine(self) -> UninitializedStateMachine<Self> {
        let inner = Inner {
            shared_storage: self,
            state: Self::initial(),
        };
        UninitializedStateMachine { inner }
    }
}

impl<T> IntoStateMachineExt for T
where
    Self: IntoStateMachine,
    for<'sub> Self::Superstate<'sub>: Superstate<Self>,
    Self::State: State<Self>,
{
}

/// A state machine that will be lazily initialized.
pub struct StateMachine<M>
where
    M: IntoStateMachine,
{
    inner: Inner<M>,
    initialized: bool,
}

impl<M> StateMachine<M>
where
    M: IntoStateMachine,
    M::State: State<M> + 'static,
    for<'sub> M::Superstate<'sub>: Superstate<M>,
{
    /// Explicitly initialize the state machine. If the state machine is already initialized
    /// this is a no-op.
    pub async fn init(&mut self)
    where
        for<'ctx> M: IntoStateMachine<Context<'ctx> = ()>,
    {
        self.init_with_context(&mut ()).await;
    }

    /// Explicitly initialize the state machine. If the state machine is already initialized
    /// this is a no-op.
    pub async fn init_with_context(&mut self, context: &mut M::Context<'_>) {
        if !self.initialized {
            self.inner.init_with_context(context).await;
            self.initialized = true;
        }
    }

    /// Handle an event. If the state machine is still uninitialized, it will be initialized
    /// before handling the event.
    pub async fn handle(&mut self, event: &M::Event<'_>)
    where
        for<'ctx> M: IntoStateMachine<Context<'ctx> = ()>,
    {
        self.handle_with_context(event, &mut ()).await;
    }

    /// Handle an event. If the state machine is still uninitialized, it will be initialized
    /// before handling the event.
    pub async fn handle_with_context(
        &mut self,
        event: &M::Event<'_>,
        context: &mut M::Context<'_>,
    ) {
        if !self.initialized {
            self.inner.init_with_context(context).await;
            self.initialized = true;
        }
        self.inner.handle_with_context(event, context).await;
    }

    pub async fn step(&mut self)
    where
        for<'evt, 'ctx> M: IntoStateMachine<Event<'evt> = (), Context<'ctx> = ()>,
    {
        self.handle_with_context(&(), &mut ()).await;
    }

    pub async fn step_with_context(&mut self, context: &mut M::Context<'_>)
    where
        for<'evt> M: IntoStateMachine<Event<'evt> = ()>,
    {
        self.handle_with_context(&(), context).await;
    }

    /// Get the current state.
    pub fn state(&self) -> &M::State {
        &self.inner.state
    }

    /// Get a reference to the [StateMachine]'s underlying type.
    ///
    /// ```
    /// # use statig::prelude::*;
    /// # #[derive(Default)]
    /// # pub struct Blinky {
    /// #     led: bool,
    /// # }
    /// #
    /// # pub struct Event;
    /// #
    /// # #[state_machine(
    /// #     initial = "State::on()",
    /// #     state(derive(Debug, PartialEq, Eq))
    /// # )]
    /// # impl Blinky {
    /// #     #[state]
    /// #     async fn on(event: &Event) -> Outcome<State> { Handled }
    /// # }
    /// #
    /// let state_machine = Blinky::default().state_machine();
    /// assert_eq!(state_machine.inner().led, false);
    /// ```
    pub fn inner(&self) -> &M {
        &self.inner.shared_storage
    }

    /// Get a mutable reference to the [StateMachine]'s underlying type.
    ///
    /// # Safety
    ///
    /// - The user is responsible for validating that mutating a
    ///   [StateMachine] does not break any invariants.
    ///
    /// ```
    /// # use statig::prelude::*;
    /// # #[derive(Default)]
    /// # pub struct Blinky {
    /// #     led: bool,
    /// # }
    /// #
    /// # pub struct Event;
    /// #
    /// # #[state_machine(initial = "State::on()")]
    /// # impl Blinky {
    /// #     #[state]
    /// #     async fn on(event: &Event) -> Outcome<State> { Handled }
    /// # }
    /// #
    /// let mut state_machine = Blinky::default().state_machine();
    ///
    /// unsafe {
    ///     state_machine.inner_mut().led = true;
    /// }
    /// ```
    pub unsafe fn inner_mut(&mut self) -> &mut M {
        &mut self.inner.shared_storage
    }

    /// Get a mutable reference to the [StateMachine]'s current state.
    ///
    /// # Safety
    ///
    /// - The user is responsible for validating that mutating a
    ///   [StateMachine] does not break any invariants.
    ///
    /// ```
    /// # use statig::prelude::*;
    /// # #[derive(Default)]
    /// # pub struct Blinky {
    /// #     led: bool,
    /// # }
    /// #
    /// # pub struct Event;
    /// #
    /// # #[state_machine(initial = "State::on()")]
    /// # impl Blinky {
    /// #     #[state]
    /// #     async fn on(event: &Event) -> Outcome<State> { Handled }
    /// # }
    /// #
    /// let mut state_machine = Blinky::default().state_machine();
    ///
    /// unsafe {
    ///     *state_machine.state_mut() = State::on();
    /// }
    /// ```
    pub unsafe fn state_mut(&mut self) -> &mut M::State {
        &mut self.inner.state
    }
}

impl<M> Clone for StateMachine<M>
where
    M: IntoStateMachine + Clone,
    M::State: Clone,
{
    fn clone(&self) -> Self {
        let inner = self.inner.clone();
        let initialized = self.initialized;
        Self { inner, initialized }
    }
}

impl<M> PartialEq for StateMachine<M>
where
    M: IntoStateMachine + PartialEq,
    M::State: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner && self.initialized == other.initialized
    }
}

impl<M> Eq for StateMachine<M>
where
    M: IntoStateMachine + PartialEq,
    M::State: PartialEq,
{
}

impl<M> Default for StateMachine<M>
where
    M: IntoStateMachine + Default,
{
    fn default() -> Self {
        let inner = Inner {
            shared_storage: M::default(),
            state: M::initial(),
        };
        Self {
            inner,
            initialized: false,
        }
    }
}

impl<M> core::ops::Deref for StateMachine<M>
where
    M: IntoStateMachine,
{
    type Target = M;

    fn deref(&self) -> &Self::Target {
        &self.inner.shared_storage
    }
}

impl<M> From<UninitializedStateMachine<M>> for StateMachine<M>
where
    M: IntoStateMachine,
{
    fn from(value: UninitializedStateMachine<M>) -> Self {
        Self {
            inner: value.inner,
            initialized: false,
        }
    }
}

impl<M> From<InitializedStateMachine<M>> for StateMachine<M>
where
    M: IntoStateMachine,
{
    fn from(value: InitializedStateMachine<M>) -> Self {
        Self {
            inner: value.inner,
            initialized: true,
        }
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<M> serde::Serialize for StateMachine<M>
where
    M: IntoStateMachine + serde::Serialize,
    M::State: serde::Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.inner.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
/// A serialized state machine can only be deserialized into an [`UninitializedStateMachine`] and can
/// then be initialized with [`init`](UninitializedStateMachine::init).
impl<'de, M> serde::Deserialize<'de> for StateMachine<M>
where
    M: IntoStateMachine + serde::Deserialize<'de>,
    M::State: serde::Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let inner: Inner<M> = Inner::deserialize(deserializer)?;
        Ok(StateMachine {
            inner,
            initialized: false,
        })
    }
}

#[cfg(feature = "bevy")]
#[cfg_attr(docsrs, doc(cfg(feature = "bevy")))]
impl<M> bevy_ecs::component::Component for StateMachine<M>
where
    Self: 'static + Send + Sync,
    M: IntoStateMachine,
{
    type Storage = bevy_ecs::component::TableStorage;
}

/// A state machine that has been initialized.
pub struct InitializedStateMachine<M>
where
    M: IntoStateMachine,
{
    inner: Inner<M>,
}

impl<M> InitializedStateMachine<M>
where
    M: IntoStateMachine,
    M::State: State<M> + 'static,
    for<'sub> M::Superstate<'sub>: Superstate<M>,
{
    /// Handle the given event.
    pub async fn handle(&mut self, event: &M::Event<'_>)
    where
        for<'ctx> M: IntoStateMachine<Context<'ctx> = ()>,
    {
        self.handle_with_context(event, &mut ()).await;
    }

    /// Handle the given event.
    pub async fn handle_with_context(&mut self, event: &M::Event<'_>, context: &mut M::Context<'_>)
    where
        M: IntoStateMachine,
    {
        self.inner.handle_with_context(event, context).await;
    }

    /// This is the same as `handle(())` in the case `Event` is of type `()`.
    pub async fn step(&mut self)
    where
        for<'evt, 'ctx> M: IntoStateMachine<Event<'evt> = (), Context<'ctx> = ()>,
    {
        self.handle(&()).await;
    }

    /// This is the same as `handle(())` in the case `Event` is of type `()`.
    pub async fn step_with_context(&mut self, context: &mut M::Context<'_>)
    where
        for<'evt> M: IntoStateMachine<Event<'evt> = ()>,
    {
        self.handle_with_context(&(), context).await;
    }

    /// Get an immutable reference to the current state of the state machine.
    pub fn state(&self) -> &M::State {
        &self.inner.state
    }

    /// Get a reference to the [InitializedStateMachine]'s underlying type.
    ///
    /// ```
    /// # use statig::prelude::*;
    /// # use futures::executor;
    /// # #[derive(Default)]
    /// # pub struct Blinky {
    /// #     led: bool,
    /// # }
    /// #
    /// # pub struct Event;
    /// #
    /// # #[state_machine(
    /// #     initial = "State::on()",
    /// #     state(derive(Debug, PartialEq, Eq))
    /// # )]
    /// # impl Blinky {
    /// #     #[state]
    /// #     async fn on(event: &Event) -> Outcome<State> { Handled }
    /// # }
    /// #
    /// # executor::block_on(async {
    /// # let uninitialized_state_machine = Blinky::default().uninitialized_state_machine();
    /// let initialized_state_machine = uninitialized_state_machine.init().await;
    /// assert_eq!(initialized_state_machine.inner().led, false);
    /// # })
    /// ```
    pub fn inner(&self) -> &M {
        &self.inner.shared_storage
    }

    /// Get a mutable reference to the [InitializedStateMachine]'s underlying type.
    ///
    /// # Safety
    ///
    /// - The user is responsible for validating that mutating a
    ///   [InitializedStateMachine] does not break any invariants.
    ///
    /// ```
    /// # use statig::prelude::*;
    /// # use futures::executor;
    /// # #[derive(Default)]
    /// # pub struct Blinky {
    /// #     led: bool,
    /// # }
    /// #
    /// # pub struct Event;
    /// #
    /// # #[state_machine(initial = "State::on()")]
    /// # impl Blinky {
    /// #     #[state]
    /// #     async fn on(event: &Event) -> Outcome<State> { Handled }
    /// # }
    /// #
    /// # executor::block_on(async {
    /// # let uninitialized_state_machine = Blinky::default().uninitialized_state_machine();
    /// let mut initialized_state_machine = uninitialized_state_machine.init().await;
    /// unsafe {
    ///     initialized_state_machine.inner_mut().led = true;
    /// }
    /// # })
    /// ```
    pub unsafe fn inner_mut(&mut self) -> &mut M {
        &mut self.inner.shared_storage
    }

    /// Get a mutable reference to the [InitializedStateMachine]'s current state.
    ///
    /// # Safety
    ///
    /// - The user is responsible for validating that mutating a
    ///   [StateMachine] does not break any invariants.
    ///
    /// ```
    /// # use statig::prelude::*;
    /// # use futures::executor;
    /// # #[derive(Default)]
    /// # pub struct Blinky {
    /// #     led: bool,
    /// # }
    /// #
    /// # pub struct Event;
    /// #
    /// # #[state_machine(initial = "State::on()")]
    /// # impl Blinky {
    /// #     #[state]
    /// #     async fn on(event: &Event) -> Outcome<State> { Handled }
    /// # }
    /// #
    /// # executor::block_on(async {
    /// let uninitialized_state_machine = Blinky::default().uninitialized_state_machine();
    /// let mut initialized_state_machine = uninitialized_state_machine.init().await;
    ///
    /// unsafe {
    ///     *initialized_state_machine.state_mut() = State::on();
    /// }
    /// # })
    /// ```
    pub unsafe fn state_mut(&mut self) -> &mut M::State {
        &mut self.inner.state
    }
}

impl<M> Clone for InitializedStateMachine<M>
where
    M: IntoStateMachine + Clone,
    M::State: Clone,
{
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<M> Debug for InitializedStateMachine<M>
where
    M: IntoStateMachine + Debug,
    M::State: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("InitializedStateMachine")
            .field("shared_storage", &self.inner.shared_storage as &dyn Debug)
            .field("state", &self.inner.state as &dyn Debug)
            .finish()
    }
}

impl<M> PartialEq for InitializedStateMachine<M>
where
    M: IntoStateMachine + PartialEq,
    M::State: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

impl<M> Eq for InitializedStateMachine<M>
where
    M: IntoStateMachine + PartialEq + Eq,
    M::State: PartialEq + Eq,
{
}

impl<M> core::ops::Deref for InitializedStateMachine<M>
where
    M: IntoStateMachine,
{
    type Target = M;

    fn deref(&self) -> &Self::Target {
        &self.inner.shared_storage
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
/// Once an [`InitializedStateMachine`] is serialized, it can only be deserialized into
/// an [`UninitializedStateMachine`] which can then be re-initialized with the
/// [`init`](UninitializedStateMachine::init) method.
impl<M> serde::Serialize for InitializedStateMachine<M>
where
    M: IntoStateMachine + serde::Serialize,
    M::State: serde::Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;

        let mut serializer = serializer.serialize_struct("StateMachine", 2)?;
        serializer.serialize_field("shared_storage", &self.inner.shared_storage)?;
        serializer.serialize_field("state", &self.inner.state)?;
        serializer.end()
    }
}

#[cfg(feature = "bevy")]
#[cfg_attr(docsrs, doc(cfg(feature = "bevy")))]
impl<M> bevy_ecs::component::Component for InitializedStateMachine<M>
where
    Self: 'static + Send + Sync,
    M: IntoStateMachine,
{
    type Storage = bevy_ecs::component::TableStorage;
}

/// A state machine that has not yet been initialized.
///
/// A state machine needs to be initialized before it can handle events. This
/// can be done by calling the [`init`](Self::init) method on it. This will
/// execute all the entry actions into the initial state.
pub struct UninitializedStateMachine<M>
where
    M: IntoStateMachine,
{
    inner: Inner<M>,
}

impl<M> UninitializedStateMachine<M>
where
    M: IntoStateMachine,
    M::State: State<M> + 'static,
    for<'sub> M::Superstate<'sub>: Superstate<M>,
{
    /// Initialize the state machine by executing all entry actions towards
    /// the initial state.
    ///
    /// ```
    /// # use statig::prelude::*;
    /// # use futures::executor;
    /// # #[derive(Default)]
    /// # pub struct Blinky {
    /// #     led: bool,
    /// # }
    /// #
    /// # pub struct Event;
    /// #
    /// # #[state_machine(initial = "State::on()")]
    /// # impl Blinky {
    /// #     #[state]
    /// #     async fn on(event: &Event) -> Outcome<State> { Handled }
    /// # }
    /// #
    /// # executor::block_on(async {
    /// let uninitialized_state_machine = Blinky::default().uninitialized_state_machine();
    ///
    /// // The uninitialized state machine is consumed to create the initialized
    /// // state machine.
    /// let initialized_state_machine = uninitialized_state_machine.init().await;
    /// # })
    /// ```
    pub async fn init(self) -> InitializedStateMachine<M>
    where
        for<'ctx> M: IntoStateMachine<Context<'ctx> = ()>,
    {
        let mut state_machine = InitializedStateMachine { inner: self.inner };
        state_machine.inner.init_with_context(&mut ()).await;
        state_machine
    }

    /// Initialize the state machine by executing all entry actions towards
    /// the initial state.
    ///
    /// ```
    /// # use statig::prelude::*;
    /// # use futures::executor;
    /// # #[derive(Default)]
    /// # pub struct Blinky {
    /// #     led: bool,
    /// # }
    /// #
    /// # pub struct Event;
    /// #
    /// # #[state_machine(initial = "State::on()")]
    /// # impl Blinky {
    /// #     #[state]
    /// #     async fn on(event: &Event) -> Outcome<State> { Handled }
    /// # }
    /// #
    /// # executor::block_on(async {
    /// let uninitialized_state_machine = Blinky::default().uninitialized_state_machine();
    ///
    /// // The uninitialized state machine is consumed to create the initialized
    /// // state machine.
    /// let initialized_state_machine = uninitialized_state_machine.init().await;
    /// # })
    /// ```
    pub async fn init_with_context(
        self,
        context: &mut M::Context<'_>,
    ) -> InitializedStateMachine<M> {
        let mut state_machine = InitializedStateMachine { inner: self.inner };
        state_machine.inner.init_with_context(context).await;
        state_machine
    }

    /// Get a reference to the [UninitializedStateMachine]'s underlying type.
    ///
    /// ```
    /// # use statig::prelude::*;
    /// # #[derive(Default)]
    /// # pub struct Blinky {
    /// #     led: bool,
    /// # }
    /// #
    /// # pub struct Event;
    /// #
    /// # #[state_machine(
    /// #     initial = "State::on()",
    /// #     state(derive(Debug, PartialEq, Eq))
    /// # )]
    /// # impl Blinky {
    /// #     #[state]
    /// #     async fn on(event: &Event) -> Outcome<State> { Handled }
    /// # }
    /// #
    /// let uninitialized_state_machine = Blinky::default().uninitialized_state_machine();
    ///
    /// assert_eq!(uninitialized_state_machine.inner().led, false);
    /// ```
    pub fn inner(&self) -> &M {
        &self.inner.shared_storage
    }

    /// Get a mutable reference to the [UninitializedStateMachine]'s underlying type.
    ///
    /// ```
    /// # use statig::prelude::*;
    /// # #[derive(Default)]
    /// # pub struct Blinky {
    /// #     led: bool,
    /// # }
    /// #
    /// # pub struct Event;
    /// #
    /// # #[state_machine(initial = "State::on()")]
    /// # impl Blinky {
    /// #     #[state]
    /// #     async fn on(event: &Event) -> Outcome<State> { Handled }
    /// # }
    /// #
    /// let mut uninitialized_state_machine = Blinky::default().uninitialized_state_machine();
    ///
    /// uninitialized_state_machine.inner_mut().led = true;
    /// ```
    pub fn inner_mut(&mut self) -> &mut M {
        &mut self.inner.shared_storage
    }

    /// Get a mutable reference to the [StateMachine]'s current state.
    ///
    /// # Safety
    ///
    /// - The user is responsible for validating that mutating a
    ///   [StateMachine] does not break any invariants.
    ///
    /// ```
    /// # use statig::prelude::*;
    /// # #[derive(Default)]
    /// # pub struct Blinky {
    /// #     led: bool,
    /// # }
    /// #
    /// # pub struct Event;
    /// #
    /// # #[state_machine(initial = "State::on()")]
    /// # impl Blinky {
    /// #     #[state]
    /// #     async fn on(event: &Event) -> Outcome<State> { Handled }
    /// # }
    /// #
    /// let mut uninitialized_state_machine = Blinky::default().uninitialized_state_machine();
    ///
    /// *uninitialized_state_machine.state_mut() = State::on();
    /// ```
    pub fn state_mut(&mut self) -> &mut M::State {
        &mut self.inner.state
    }
}

impl<M> Clone for UninitializedStateMachine<M>
where
    M: IntoStateMachine + Clone,
    M::State: Clone,
{
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<M> Debug for UninitializedStateMachine<M>
where
    M: IntoStateMachine + Debug,
    M::State: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("UnInitializedStateMachine")
            .field("shared_storage", &self.inner.shared_storage as &dyn Debug)
            .field("state", &self.inner.state as &dyn Debug)
            .finish()
    }
}

impl<M> PartialEq for UninitializedStateMachine<M>
where
    M: IntoStateMachine + PartialEq,
    M::State: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

impl<M> Eq for UninitializedStateMachine<M>
where
    M: IntoStateMachine + PartialEq + Eq,
    M::State: PartialEq + Eq,
{
}

impl<M> core::ops::Deref for UninitializedStateMachine<M>
where
    M: IntoStateMachine,
{
    type Target = M;

    fn deref(&self) -> &Self::Target {
        &self.inner.shared_storage
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<M> serde::Serialize for UninitializedStateMachine<M>
where
    M: IntoStateMachine + serde::Serialize,
    M::State: serde::Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.inner.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
/// A serialized state machine can only be deserialized into an [`UninitializedStateMachine`] and can
/// then be initialized with [`init`](UninitializedStateMachine::init).
impl<'de, M> serde::Deserialize<'de> for UninitializedStateMachine<M>
where
    M: IntoStateMachine + serde::Deserialize<'de>,
    M::State: serde::Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let inner: Inner<M> = Inner::deserialize(deserializer)?;
        Ok(UninitializedStateMachine { inner })
    }
}