Skip to main content

02_vending/
main.rs

1//! Example: Vending Machine
2#![allow(clippy::unwrap_used)]
3#[allow(clippy::wildcard_imports)]
4use essm::*;
5
6// ── Items ──────────────────────────────────────────────────────────
7
8#[derive(Debug, Clone, Copy)]
9struct Item {
10    name: &'static str,
11    cost: u32,
12}
13
14const ITEMS: &[Item] = &[
15    Item {
16        name: "Chips",
17        cost: 50,
18    },
19    Item {
20        name: "Soda",
21        cost: 75,
22    },
23    Item {
24        name: "Candy",
25        cost: 25,
26    },
27];
28
29// ── Error type ──────────────────────────────────────────────────────
30
31#[derive(Debug)]
32enum VendError {
33    NotEnoughCredit,
34}
35impl StateError for VendError {}
36
37// ── States ──────────────────────────────────────────────────────────
38
39#[derive(Debug, Default)]
40struct Idle;
41impl State for Idle {
42    fn enter(&self, _ctx: &dyn Any) -> Result<(), Infallible> {
43        println!("  Machine ready. INSERT COIN");
44        Ok(())
45    }
46}
47
48impl Idle {
49    fn start(self) -> HasCredit {
50        println!("> start");
51        self.try_transition().unwrap()
52    }
53}
54
55#[derive(Debug)]
56struct HasCredit {
57    amount: u32,
58}
59
60impl State for HasCredit {
61    fn enter(&self, _ctx: &dyn Any) -> Result<(), Infallible> {
62        println!("  Credit: {}¢", self.amount);
63        Ok(())
64    }
65}
66
67impl HasCredit {
68    fn insert_coin(self) -> HasCredit {
69        println!("> insert coin (25¢)");
70        self.try_transition().unwrap()
71    }
72
73    fn select(self, item: &Item) -> TransitionResult<HasCredit, Dispensing, VendError> {
74        println!("> select {} ({}¢)", item.name, item.cost);
75        self.try_transition_with(item)
76    }
77
78    fn refund(self) -> Idle {
79        println!("> refund");
80        self.try_transition().unwrap()
81    }
82}
83
84#[derive(Debug)]
85struct Dispensing {
86    item: &'static str,
87    price: u32,
88    change: u32,
89}
90
91impl State for Dispensing {
92    fn enter(&self, _ctx: &dyn Any) -> Result<(), Infallible> {
93        let w = "═".repeat(18);
94        println!("  ╔{w}╗");
95        println!("  ║{:<18}║", "RECEIPT");
96        println!("  ║{:<18}║", format!("Item:  {}", self.item));
97        println!("  ║{:<18}║", format!("Price: {}¢", self.price));
98        println!("  ║{:<18}║", format!("Change: {}¢", self.change));
99        println!("  ╚{w}╝");
100        Ok(())
101    }
102}
103
104impl Dispensing {
105    fn dispense(self) -> Idle {
106        println!("> dispense");
107        self.try_transition().unwrap()
108    }
109}
110
111// ── Transitions ─────────────────────────────────────────────────────
112impl Transition<Idle> for Primordial {
113    fn change(self, _ctx: &dyn Any) -> TransitionResult<Primordial, Idle, Infallible> {
114        Ok(Idle)
115    }
116}
117
118impl Transition<HasCredit> for Idle {
119    fn change(self, _ctx: &dyn Any) -> TransitionResult<Idle, HasCredit> {
120        Ok(HasCredit { amount: 0 })
121    }
122}
123
124impl Transition<HasCredit> for HasCredit {
125    fn change(self, _ctx: &dyn Any) -> TransitionResult<HasCredit, HasCredit> {
126        Ok(HasCredit {
127            amount: self.amount + 25,
128        })
129    }
130}
131
132impl Transition<Dispensing, VendError, Infallible> for HasCredit {
133    fn change(self, item: &dyn Any) -> TransitionResult<HasCredit, Dispensing, VendError> {
134        let item = item.downcast_ref::<Item>().unwrap();
135        if self.amount >= item.cost {
136            Ok(Dispensing {
137                item: item.name,
138                price: item.cost,
139                change: self.amount - item.cost,
140            })
141        } else {
142            ErrorState::err_origin(VendError::NotEnoughCredit, self)
143        }
144    }
145}
146
147impl Transition<Idle> for HasCredit {
148    fn change(self, _ctx: &dyn Any) -> TransitionResult<HasCredit, Idle> {
149        println!("  Refunding {}¢", self.amount);
150        Ok(Idle)
151    }
152}
153
154impl Transition<Idle> for Dispensing {
155    fn change(self, _ctx: &dyn Any) -> TransitionResult<Dispensing, Idle> {
156        println!("  Dispensed. Enjoy your {}.", self.item);
157        Ok(Idle)
158    }
159}
160
161// ── Error recovery ──────────────────────────────────────────────────
162
163impl Transition<HasCredit> for ErrorState<VendError, HasCredit, Dispensing> {
164    fn change(self, _ctx: &dyn Any) -> TransitionResult<Self, HasCredit> {
165        match self.at {
166            FailedAt::Origin(state) => Ok(state),
167            _ => panic!("expected origin in recovery"),
168        }
169    }
170}
171
172trait RecoverToHasCredit {
173    fn recover(self) -> HasCredit;
174}
175
176impl RecoverToHasCredit for ErrorState<VendError, HasCredit, Dispensing> {
177    fn recover(self) -> HasCredit {
178        println!("> recover");
179        self.try_transition().unwrap()
180    }
181}
182
183// ── Main ────────────────────────────────────────────────────────────
184
185fn main() {
186    println!("=== Vending Machine ===\n");
187
188    let mut machine = Idle::new();
189
190    // ── Purchase Chips (50¢) ──
191    println!("-- Purchase {} --", ITEMS[0].name);
192    let mut has_credits = machine.start();
193    for _ in 0..2 {
194        has_credits = has_credits.insert_coin(); // 50¢
195    }
196
197    let dispensing: Dispensing = has_credits.select(&ITEMS[0]).unwrap();
198    machine = dispensing.dispense();
199
200    // ── Purchase Soda (75¢) ──
201    println!("\n-- Purchase {} --", ITEMS[1].name);
202    let mut has_credits = machine.start();
203    for _ in 0..3 {
204        has_credits = has_credits.insert_coin(); // 75¢
205    }
206    let dispensing: Dispensing = has_credits.select(&ITEMS[1]).unwrap();
207    machine = dispensing.dispense();
208
209    println!("\n-- Refund --");
210    let mut has_credits = machine.start();
211    has_credits = has_credits.insert_coin(); // 25¢, then refund
212    machine = has_credits.refund();
213
214    // ── Insufficient credit, then recover ──
215    println!("\n-- Insufficient credit --");
216    let mut has_credits = machine.start();
217    has_credits = has_credits.insert_coin(); // 25¢
218    match has_credits.select(&ITEMS[0]) {
219        Ok(dispensing) => {
220            machine = dispensing.dispense();
221        }
222        Err(error) => {
223            println!(
224                "  Not enough credit for {} (need {}¢, have 25¢)!",
225                ITEMS[0].name, ITEMS[0].cost
226            );
227            has_credits = error.recover(); // back to HasCredit
228            has_credits = has_credits.insert_coin(); // 50¢ total
229            let dispensing: Dispensing = has_credits.select(&ITEMS[0]).unwrap();
230            machine = dispensing.dispense();
231        }
232    }
233
234    println!("\n  Machine ready for next customer.");
235    let _ = machine; // a real implementaition would loop on machine
236}