lightproc/
proc_state.rs

1//!
2//! State layer for lightproc implementation
3//!
4//! Contains trait bounds and state wrapping code
5//!
6//! # Example
7//! ```rust
8//! use lightproc::proc_state::State;
9//! use crate::lightproc::proc_state::AsAny;
10//!
11//! #[derive(Clone)]
12//! pub struct SharedState {
13//!     name: String,
14//!     surname: String,
15//!     id: u64,
16//! }
17//!
18//!
19//! let mut s = SharedState {
20//!     name: "Riemann".to_string(),
21//!     surname: "Sum".to_string(),
22//!     id: 123
23//! };
24//!
25//! s.as_any();
26//! ```
27
28use std::any::Any;
29
30use std::fmt::{Error, Formatter};
31
32use std::fmt;
33use std::sync::{Arc, Mutex};
34
35///
36/// State trait to implement a state for Bastion
37pub trait State: Send + Sync + AsAny + 'static {}
38
39///
40/// Blanket implementation for the state when rules apply
41impl<T> State for T where T: Send + Sync + 'static {}
42
43///
44/// Default debug implementation for dynamically dispatched state
45impl fmt::Debug for dyn State {
46    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
47        f.write_fmt(format_args!("State :: {:?}", self.type_id()))
48    }
49}
50
51///
52/// Generic protection type where state is stored as is.
53/// This allows us to share the state between the threads (both by ref and by value).
54/// All state implementors bound to use this.
55pub type ProcState = Arc<Mutex<dyn State>>;
56
57///
58/// Generic dynamic programming construct which allows us to downcast to the typeless level.
59/// And do costly conversion between types if possible.
60pub trait AsAny {
61    ///
62    /// Downcast implemented type to Any.
63    fn as_any(&mut self) -> &mut dyn Any;
64}
65
66///
67/// Blanket implementation for Any conversion if type is implementing Any.
68impl<T: Any> AsAny for T {
69    fn as_any(&mut self) -> &mut dyn Any {
70        self
71    }
72}
73
74// ------------------------------------------------------
75// State related types are below
76// ------------------------------------------------------
77
78///
79/// Empty proc state which is an heap allocated empty struct.
80pub type EmptyProcState = Box<EmptyState>;
81
82///
83/// Base construct for empty state struct.
84#[derive(Debug)]
85pub struct EmptyState;