rust/src/test/run-pass/pipe-bank-proto.rs

109 lines
2.5 KiB
Rust
Raw Normal View History

2012-07-06 15:42:06 -05:00
// xfail-pretty
// An example of the bank protocol from eholk's blog post.
//
// http://theincredibleholk.wordpress.com/2012/07/06/rusty-pipes/
import pipes::try_recv;
2012-07-06 15:42:06 -05:00
type username = ~str;
type password = ~str;
2012-07-06 15:42:06 -05:00
type money = float;
type amount = float;
proto! bank (
2012-07-06 15:42:06 -05:00
login:send {
login(username, password) -> login_response
}
login_response:recv {
ok -> connected,
invalid -> login
}
connected:send {
deposit(money) -> connected,
withdrawal(amount) -> withdrawal_response
}
withdrawal_response:recv {
money(money) -> connected,
insufficient_funds -> connected
}
)
2012-07-06 15:42:06 -05:00
macro_rules! move_it (
{ $x:expr } => { unsafe { let y <- *ptr::addr_of($x); y } }
)
2012-07-06 15:42:06 -05:00
fn switch<T: send, U>(+endp: pipes::recv_packet<T>,
2012-08-20 14:23:37 -05:00
f: fn(+Option<T>) -> U) -> U {
f(pipes::try_recv(endp))
}
fn move_it<T>(-x: T) -> T { x }
macro_rules! follow (
2012-08-22 19:24:52 -05:00
{
$($message:path$(($($x: ident),+))||* -> $next:ident $e:expr)+
} => (
|m| match move m {
2012-08-20 14:23:37 -05:00
$(Some($message($($($x,)+)* next)) => {
2012-08-22 19:24:52 -05:00
let $next = move_it!(next);
$e })+
_ => { fail }
}
);
)
fn client_follow(+bank: bank::client::login) {
import bank::*;
let bank = client::login(bank, ~"theincredibleholk", ~"1234");
2012-08-22 19:24:52 -05:00
let bank = switch(bank, follow! (
ok -> connected { connected }
invalid -> _next { fail ~"bank closed the connected" }
2012-08-22 19:24:52 -05:00
));
let bank = client::deposit(bank, 100.00);
let bank = client::withdrawal(bank, 50.00);
2012-08-22 19:24:52 -05:00
switch(bank, follow! (
money(m) -> _next {
io::println(~"Yay! I got money!");
}
insufficient_funds -> _next {
fail ~"someone stole my money"
}
2012-08-22 19:24:52 -05:00
));
}
2012-07-06 15:42:06 -05:00
fn bank_client(+bank: bank::client::login) {
import bank::*;
let bank = client::login(bank, ~"theincredibleholk", ~"1234");
2012-08-06 14:34:08 -05:00
let bank = match try_recv(bank) {
2012-08-20 14:23:37 -05:00
Some(ok(connected)) => {
2012-08-22 19:24:52 -05:00
move_it!(connected)
2012-07-06 15:42:06 -05:00
}
2012-08-20 14:23:37 -05:00
Some(invalid(_)) => { fail ~"login unsuccessful" }
None => { fail ~"bank closed the connection" }
2012-07-06 15:42:06 -05:00
};
let bank = client::deposit(bank, 100.00);
let bank = client::withdrawal(bank, 50.00);
2012-08-06 14:34:08 -05:00
match try_recv(bank) {
2012-08-20 14:23:37 -05:00
Some(money(m, _)) => {
io::println(~"Yay! I got money!");
2012-07-06 15:42:06 -05:00
}
2012-08-20 14:23:37 -05:00
Some(insufficient_funds(_)) => {
fail ~"someone stole my money"
2012-07-06 15:42:06 -05:00
}
2012-08-20 14:23:37 -05:00
None => {
fail ~"bank closed the connection"
2012-07-06 15:42:06 -05:00
}
}
}
fn main() {
}