1use std::collections::VecDeque;
4
5use behavior::{Actions, Address, Behavior, Creations, NoBirths, Protocol, SendsFor, User};
6use behavior::{Never, Step, Stopped};
7
8use crate::DeliveryRoute;
9use crate::inputs::HeldInputs;
10use crate::retention::{InputLimit, InputRetention};
11
12pub enum Move<P> {
13 Stay,
14 Goto(P),
15 Defer,
16 Stop,
17}
18
19#[derive(Clone, PartialEq, Eq, thiserror::Error)]
25#[error("machine rejected its mailbox input: {cause}")]
26pub struct MachineError<A, M, E> {
27 pub event: User<A, M>,
29 #[source]
31 pub cause: E,
32}
33
34impl<A, M, E: core::fmt::Debug> core::fmt::Debug for MachineError<A, M, E> {
35 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36 formatter
37 .debug_struct("MachineError")
38 .field("event", &"<retained>")
39 .field("cause", &self.cause)
40 .finish()
41 }
42}
43
44pub struct Machine<A: Address, S, M, P, E, R = ()> {
54 state: S,
55 phase: P,
56 on: fn(P, &mut S, &M) -> Result<Move<P>, E>,
57 held: VecDeque<User<A, M>>,
58 retention: R,
59}
60
61impl<A, S, M, P, E, R> Clone for Machine<A, S, M, P, E, R>
62where
63 A: Address,
64 S: Clone,
65 M: Clone,
66 P: Clone,
67 R: Clone,
68{
69 fn clone(&self) -> Self {
70 Self {
71 state: self.state.clone(),
72 phase: self.phase.clone(),
73 on: self.on,
74 held: self.held.clone(),
75 retention: self.retention.clone(),
76 }
77 }
78}
79
80impl<A, S, M, P, E, R> behavior::BehaviorBase for Machine<A, S, M, P, E, R>
81where
82 A: Address,
83{
84 type Base = Self;
85
86 fn base(&self) -> &Self {
87 self
88 }
89}
90
91impl<A: Address, S, M, P: Copy + PartialEq, E> Machine<A, S, M, P, E> {
92 #[must_use]
100 pub fn new(state: S, phase: P, on: fn(P, &mut S, &M) -> Result<Move<P>, E>) -> Self {
101 Self {
102 state,
103 phase,
104 on,
105 held: VecDeque::new(),
106 retention: (),
107 }
108 }
109
110 #[must_use]
127 pub fn bounded<R>(
128 state: S,
129 phase: P,
130 on: fn(P, &mut S, &M) -> Result<Move<P>, E>,
131 retention: InputLimit<R>,
132 ) -> Machine<A, S, M, P, E, InputLimit<R>>
133 where
134 R: DeliveryRoute + Clone,
135 R::Protocol: Protocol<Addr = A, Msg = User<A, M>>,
136 R::Sends: SendsFor<User<A, M>>,
137 {
138 Machine {
139 state,
140 phase,
141 on,
142 held: VecDeque::new(),
143 retention,
144 }
145 }
146}
147
148impl<A: Address, S, M, P: Copy + PartialEq, E, R> Machine<A, S, M, P, E, R> {
149 #[must_use]
150 pub fn state(&self) -> &S {
151 &self.state
152 }
153
154 #[must_use]
155 pub fn phase(&self) -> P {
156 self.phase
157 }
158
159 #[must_use]
160 pub fn held(&self) -> usize {
161 self.held.len()
162 }
163
164 #[must_use]
172 pub fn take(&mut self) -> VecDeque<User<A, M>> {
173 core::mem::take(&mut self.held)
174 }
175
176 fn drain(&mut self) -> Result<Step<Never, Stopped>, MachineError<A, M, E>> {
177 let mut inputs = HeldInputs {
178 unread: core::mem::take(&mut self.held),
179 held: &mut self.held,
180 };
181 while let Some(event) = inputs.unread.front() {
182 let decision = (self.on)(self.phase, &mut self.state, &event.message);
183 let Some(event) = inputs.unread.pop_front() else {
184 break;
185 };
186 match decision {
187 Err(cause) => return Err(MachineError { event, cause }),
188 Ok(Move::Stay) => {}
189 Ok(Move::Defer) => inputs.held.push_back(event),
190 Ok(Move::Stop) => return Ok(Step::Stop(Stopped)),
191 Ok(Move::Goto(next)) => {
192 let previous = core::mem::replace(&mut self.phase, next);
193 if next != previous {
194 inputs.unread.append(inputs.held);
195 }
196 }
197 }
198 }
199 Ok(Step::Continue)
200 }
201}
202
203impl<A: Address, S, M, P, E, R> behavior::Protocol for Machine<A, S, M, P, E, R> {
204 type Addr = A;
205 type Msg = M;
206}
207
208impl<A, S, M, P, E, R> Behavior for Machine<A, S, M, P, E, R>
209where
210 A: Address,
211 P: Copy + PartialEq,
212 R: InputRetention<A, M>,
213 R::Sends: SendsFor<User<A, M>>,
214{
215 type Protocol = Self;
216 type Event = User<A, M>;
217 type Sends = R::Sends;
218 type Ph = Never;
219 type Error = MachineError<A, M, E>;
220 type Birth = NoBirths;
221
222 fn init(
223 &mut self,
224 _: behavior::InitializationTurn,
225 ) -> Result<Actions<A, Never, Self::Sends, NoBirths>, Self::Error> {
226 Ok(Actions::cont())
227 }
228
229 fn transition(
230 &mut self,
231 _: behavior::ActiveTurn,
232 event: Self::Event,
233 ) -> Result<Actions<A, Never, Self::Sends, NoBirths>, Self::Error> {
234 match (self.on)(self.phase, &mut self.state, &event.message) {
235 Err(cause) => Err(MachineError { event, cause }),
236 Ok(Move::Stay) => Ok(Actions::cont()),
237 Ok(Move::Defer) => Ok(Actions::new(
238 self.retention.hold(&mut self.held, event),
239 Creations::empty(),
240 Step::Continue,
241 )),
242 Ok(Move::Stop) => Ok(Actions::stop()),
243 Ok(Move::Goto(next)) => {
244 let previous = core::mem::replace(&mut self.phase, next);
245 if next == previous {
246 return Ok(Actions::cont());
247 }
248 self.drain().map(Actions::just)
249 }
250 }
251 }
252}