25 lines
741 B
Plaintext
25 lines
741 B
Plaintext
# An `ensures` names what the function returns, and `old` within it is what an
|
|
# expression was where the `ensures` was reached.
|
|
import std::io;
|
|
|
|
struct wallet { var balance: u64; }
|
|
|
|
def withdraw(from: &mut wallet, amount: u64): u64 {
|
|
expects(amount <= from.balance, "A wallet gives no more than it holds.");
|
|
ensures(left: left == old(from.balance) - amount);
|
|
from.balance -= amount;
|
|
return from.balance;
|
|
}
|
|
|
|
def withdraw_wrongly(from: &mut wallet, amount: u64): u64 {
|
|
ensures(left: left == old(from.balance) - amount);
|
|
from.balance -= amount;
|
|
return from.balance + 1;
|
|
}
|
|
|
|
def main(): void {
|
|
var held := wallet { balance = 10 };
|
|
io::println($"{withdraw(&mut held, 3)}");
|
|
io::println($"{withdraw_wrongly(&mut held, 3)}");
|
|
}
|