-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathatm.rs
More file actions
91 lines (77 loc) · 2.4 KB
/
atm.rs
File metadata and controls
91 lines (77 loc) · 2.4 KB
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
#[macro_use] extern crate session_types;
use session_types::*;
use std::thread::spawn;
type Id = String;
type Atm = Recv<Id, Choose<(Rec<AtmInner>, Eps)>>;
type AtmInner = Offer<(AtmDeposit,
AtmWithdraw,
Eps)>;
type AtmDeposit = Recv<u64, Send<u64, Var<Z>>>;
type AtmWithdraw = Recv<u64, Choose<(Var<Z>, Var<Z>)>>;
type Client = <Atm as HasDual>::Dual;
fn approved(id: &Id) -> bool {
!id.is_empty()
}
fn atm(c: Chan<(), Atm>) {
let mut c = {
let (c, id) = c.recv();
if !approved(&id) {
c.sel2().close();
return;
}
c.sel1().enter()
};
let mut balance = 0;
loop {
c = match c.offer() {
Branch3::B1(c) => {
let (c, amt) = c.recv();
balance = amt;
c.send(balance).zero() // c.send(new_bal): Chan<(AtmInner, ()) Var<Z>>
},
Branch3::B2(c) => {
let (c, amt) = c.recv();
if amt <= balance {
balance = balance - amt;
c.sel1().zero()
} else {
c.sel2().zero()
}
},
Branch3::B3(c) => { c.close(); break }
};
}
}
fn deposit_client(c: Chan<(), Client>) {
let c = match c.send("Deposit Client".to_string()).offer() {
B1(c) => c.enter(),
B2(_) => panic!("deposit_client: expected to be approved")
};
let (c, new_balance) = c.sel1().send(200).recv();
println!("deposit_client: new balance: {}", new_balance);
c.zero().sel3().close();
}
fn withdraw_client(c: Chan<(), Client>) {
let c = match c.send("Withdraw Client".to_string()).offer() {
B1(c) => c.enter(),
B2(_) => panic!("withdraw_client: expected to be approved")
};
match c.sel2().send(100).offer() {
B1(c) => {
println!("withdraw_client: Successfully withdrew 100");
c.zero().sel3().close();
}
B2(c) => {
println!("withdraw_client: Could not withdraw. Depositing instead.");
c.zero().sel1().send(50).recv().0.zero().sel3().close();
}
}
}
fn main() {
let (atm_chan, client_chan) = session_channel();
spawn(|| atm(atm_chan));
deposit_client(client_chan);
let (atm_chan, client_chan) = session_channel();
spawn(|| atm(atm_chan));
withdraw_client(client_chan);
}