Add comments to example, remove unnecessary checks
@@ -6,27 +6,27 @@ extern crate mirai_annotations;
pub mod foreign_contracts;
struct Cart {
- items: Vec<i32>
+ /// We model a shopping cart as Vector of items.
+ /// We are interested in the cost of those items
+ /// for checkout purposes so we only add the items'
+ /// cost (as an i32) to the cart.
+ items: Vec<i32>,
}
impl Cart {
fn new() -> Cart {
- Cart {
- items: Vec::new(),
- }
+ Cart { items: Vec::new() }
}
fn add_item(&mut self, value: i32) {
+ // We don't want items with zero or negative
+ // prices to be added to the cart
precondition!(value > 0);
- let old_len = self.items.len();
self.items.push(value);
- verify!(self.items.len() == old_len + 1);
}
fn remove_item(&mut self) -> Option<i32> {
- let old_len = self.items.len();
let res = self.items.pop();
- verify!(self.items.len() == 0 || self.items.len() == old_len - 1);
res
}
@@ -41,14 +41,17 @@ impl Cart {
while i < len {
let x = self.items.get(i);
match x {
- None => {},
+ None => {}
Some(item) => {
sum = sum + *item;
}
}
i += 1;
}
- verify!(len <= 0 || sum > 0);
+ // We check the following condition: Either the
+ // cart is empty or the sum value of the items
+ // in the cart is non-negative.
+ verify!(len == 0 || sum > 0);
sum
}
}
@@ -56,17 +59,19 @@ impl Cart {
fn main() {
let mut cart = Cart::new();
- let old_num_items = cart.num_items();
cart.add_item(10);
- verify!(cart.num_items() == old_num_items + 1);
let _ = cart.remove_item();
- verify!(cart.num_items() == old_num_items);
cart.add_item(20);
cart.add_item(30);
cart.add_item(40);
+ let item_count = cart.num_items();
let total = cart.checkout();
+
+ // We check that the cart's total value
+ // is greater than zero, as we would expect
+ // for a non-empty cart.
verify!(total > 0);
- println!("Total: {}", total);
+ println!("Item count: {} | Total price: {}", item_count, total);
}
