Bill

Struct Bill 

Source
pub struct Bill<P> {
    pub items_by_tax: BTreeMap<Tax, ItemList<P>>,
}
Expand description

This is where the magic happens.

Fields§

§items_by_tax: BTreeMap<Tax, ItemList<P>>

Implementations§

Source§

impl<P: BillProduct> Bill<P>

Source

pub fn new() -> Self

Instantiates a new Bill

Examples found in repository?
examples/catalogue.rs (line 49)
37fn main() {
38    let coffee = Product::new("Coffee", c(250), 0.19);
39    let tee = Product::new("Tea", c(175), 0.19);
40    let water = Product::new("Water", c(61), 0.19);
41    let applejuice = Product::new("AppleJuice", c(164), 0.19);
42    let orangejuice = Product::new("OrangeJuice", c(186), 0.19);
43    let bagel = Product::new("Bagel", c(219), 0.19);
44    let sandwich = Product::new("Sandwich", c(340), 0.19);
45    let pie = Product::new("pie", c(94), 0.19);
46    let soup = Product::new("Soup", c(310), 0.19);
47    let service = Product::new("Service", c(800), 0.00);
48
49    let mut offer = Bill::new();
50    offer.add_item(8., water);
51    offer.add_item(4., applejuice);
52    offer.add_item(4., orangejuice);
53    offer.add_item(40., sandwich);
54    offer.add_item(2., service);
55
56    let mut invoice = Bill::new();
57    invoice.add_item(2., water);
58    invoice.add_item(0., applejuice);
59    invoice.add_item(2., orangejuice);
60    invoice.add_item(50., sandwich);
61    invoice.add_item(2.5, service);
62
63    let mut invoice2 = Bill::new();
64    invoice2.add_item(99.0, Product::new("Red Ballons", c(99), 0.19));
65
66    #[cfg(not(feature = "serialization"))]
67    {
68        print("offer", &offer);
69        print("invoice", &invoice);
70        print("invoice2", &invoice2);
71    }
72    #[cfg(feature = "serialization")]
73    {
74        println!("{}", serde_json::to_string_pretty(&offer).unwrap());
75        println!("{}", serde_json::to_string_pretty(&invoice).unwrap());
76        println!("{}", serde_json::to_string_pretty(&invoice2).unwrap());
77    }
78}
Source

pub fn to_items_with_tax(&self) -> BTreeMap<Tax, &BillItem<P>>

Source

pub fn as_items_with_tax(&self) -> Vec<(Tax, &BillItem<P>)>

Returns a Vec of Tax and BillItem

Source

pub fn as_items(&self) -> Vec<&BillItem<P>>

Returns a Vec of BillItem

Source

pub fn add(&mut self, item: BillItem<P>)

Adds a new BillItem to the list.

Source

pub fn add_item(&mut self, amount: Amount, product: P)

Instantiates and adds a new BillItem to the list.

Examples found in repository?
examples/catalogue.rs (line 50)
37fn main() {
38    let coffee = Product::new("Coffee", c(250), 0.19);
39    let tee = Product::new("Tea", c(175), 0.19);
40    let water = Product::new("Water", c(61), 0.19);
41    let applejuice = Product::new("AppleJuice", c(164), 0.19);
42    let orangejuice = Product::new("OrangeJuice", c(186), 0.19);
43    let bagel = Product::new("Bagel", c(219), 0.19);
44    let sandwich = Product::new("Sandwich", c(340), 0.19);
45    let pie = Product::new("pie", c(94), 0.19);
46    let soup = Product::new("Soup", c(310), 0.19);
47    let service = Product::new("Service", c(800), 0.00);
48
49    let mut offer = Bill::new();
50    offer.add_item(8., water);
51    offer.add_item(4., applejuice);
52    offer.add_item(4., orangejuice);
53    offer.add_item(40., sandwich);
54    offer.add_item(2., service);
55
56    let mut invoice = Bill::new();
57    invoice.add_item(2., water);
58    invoice.add_item(0., applejuice);
59    invoice.add_item(2., orangejuice);
60    invoice.add_item(50., sandwich);
61    invoice.add_item(2.5, service);
62
63    let mut invoice2 = Bill::new();
64    invoice2.add_item(99.0, Product::new("Red Ballons", c(99), 0.19));
65
66    #[cfg(not(feature = "serialization"))]
67    {
68        print("offer", &offer);
69        print("invoice", &invoice);
70        print("invoice2", &invoice2);
71    }
72    #[cfg(feature = "serialization")]
73    {
74        println!("{}", serde_json::to_string_pretty(&offer).unwrap());
75        println!("{}", serde_json::to_string_pretty(&invoice).unwrap());
76        println!("{}", serde_json::to_string_pretty(&invoice2).unwrap());
77    }
78}
Source

pub fn sums_by_tax(&self) -> BTreeMap<Tax, Money>

Source

pub fn gross_total(&self) -> Money

Examples found in repository?
examples/catalogue.rs (line 31)
24fn print(title: &str, bill: &Bill<Product<'_>>) {
25    println!("{}:", title);
26    for (tax, items) in &bill.items_by_tax {
27        println!("  {}%", tax);
28        print_items(items);
29    }
30    println!("---------------------------------------");
31    println!("       {}", bill.gross_total().postfix());
32    println!("     + {} (tax)", bill.tax_total().postfix());
33    println!("   net {}", bill.net_total().postfix());
34    println!();
35}
Source

pub fn tax_total(&self) -> Money

Examples found in repository?
examples/catalogue.rs (line 32)
24fn print(title: &str, bill: &Bill<Product<'_>>) {
25    println!("{}:", title);
26    for (tax, items) in &bill.items_by_tax {
27        println!("  {}%", tax);
28        print_items(items);
29    }
30    println!("---------------------------------------");
31    println!("       {}", bill.gross_total().postfix());
32    println!("     + {} (tax)", bill.tax_total().postfix());
33    println!("   net {}", bill.net_total().postfix());
34    println!();
35}
Source

pub fn net_total(&self) -> Money

Examples found in repository?
examples/catalogue.rs (line 33)
24fn print(title: &str, bill: &Bill<Product<'_>>) {
25    println!("{}:", title);
26    for (tax, items) in &bill.items_by_tax {
27        println!("  {}%", tax);
28        print_items(items);
29    }
30    println!("---------------------------------------");
31    println!("       {}", bill.gross_total().postfix());
32    println!("     + {} (tax)", bill.tax_total().postfix());
33    println!("   net {}", bill.net_total().postfix());
34    println!();
35}

Methods from Deref<Target = BTreeMap<Tax, ItemList<P>>>§

1.0.0 · Source

pub fn get<Q>(&self, key: &Q) -> Option<&V>
where K: Borrow<Q> + Ord, Q: Ord + ?Sized,

Returns a reference to the value corresponding to the key.

The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.

§Examples
use std::collections::BTreeMap;

let mut map = BTreeMap::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);
1.40.0 · Source

pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
where K: Borrow<Q> + Ord, Q: Ord + ?Sized,

Returns the key-value pair corresponding to the supplied key. This is potentially useful:

  • for key types where non-identical keys can be considered equal;
  • for getting the &K stored key value from a borrowed &Q lookup key; or
  • for getting a reference to a key with the same lifetime as the collection.

The supplied key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.

§Examples
use std::cmp::Ordering;
use std::collections::BTreeMap;

#[derive(Clone, Copy, Debug)]
struct S {
    id: u32,
    name: &'static str, // ignored by equality and ordering operations
}

impl PartialEq for S {
    fn eq(&self, other: &S) -> bool {
        self.id == other.id
    }
}

impl Eq for S {}

impl PartialOrd for S {
    fn partial_cmp(&self, other: &S) -> Option<Ordering> {
        self.id.partial_cmp(&other.id)
    }
}

impl Ord for S {
    fn cmp(&self, other: &S) -> Ordering {
        self.id.cmp(&other.id)
    }
}

let j_a = S { id: 1, name: "Jessica" };
let j_b = S { id: 1, name: "Jess" };
let p = S { id: 2, name: "Paul" };
assert_eq!(j_a, j_b);

let mut map = BTreeMap::new();
map.insert(j_a, "Paris");
assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
assert_eq!(map.get_key_value(&p), None);
1.66.0 · Source

pub fn first_key_value(&self) -> Option<(&K, &V)>
where K: Ord,

Returns the first key-value pair in the map. The key in this pair is the minimum key in the map.

§Examples
use std::collections::BTreeMap;

let mut map = BTreeMap::new();
assert_eq!(map.first_key_value(), None);
map.insert(1, "b");
map.insert(2, "a");
assert_eq!(map.first_key_value(), Some((&1, &"b")));
1.66.0 · Source

pub fn last_key_value(&self) -> Option<(&K, &V)>
where K: Ord,

Returns the last key-value pair in the map. The key in this pair is the maximum key in the map.

§Examples
use std::collections::BTreeMap;

let mut map = BTreeMap::new();
map.insert(1, "b");
map.insert(2, "a");
assert_eq!(map.last_key_value(), Some((&2, &"a")));
1.0.0 · Source

pub fn contains_key<Q>(&self, key: &Q) -> bool
where K: Borrow<Q> + Ord, Q: Ord + ?Sized,

Returns true if the map contains a value for the specified key.

The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.

§Examples
use std::collections::BTreeMap;

let mut map = BTreeMap::new();
map.insert(1, "a");
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);
1.17.0 · Source

pub fn range<T, R>(&self, range: R) -> Range<'_, K, V>
where T: Ord + ?Sized, K: Borrow<T> + Ord, R: RangeBounds<T>,

Constructs a double-ended iterator over a sub-range of elements in the map. The simplest way is to use the range syntax min..max, thus range(min..max) will yield elements from min (inclusive) to max (exclusive). The range may also be entered as (Bound<T>, Bound<T>), so for example range((Excluded(4), Included(10))) will yield a left-exclusive, right-inclusive range from 4 to 10.

§Panics

Panics if range start > end. Panics if range start == end and both bounds are Excluded.

§Examples
use std::collections::BTreeMap;
use std::ops::Bound::Included;

let mut map = BTreeMap::new();
map.insert(3, "a");
map.insert(5, "b");
map.insert(8, "c");
for (&key, &value) in map.range((Included(&4), Included(&8))) {
    println!("{key}: {value}");
}
assert_eq!(Some((&5, &"b")), map.range(4..).next());
1.0.0 · Source

pub fn iter(&self) -> Iter<'_, K, V>

Gets an iterator over the entries of the map, sorted by key.

§Examples
use std::collections::BTreeMap;

let mut map = BTreeMap::new();
map.insert(3, "c");
map.insert(2, "b");
map.insert(1, "a");

for (key, value) in map.iter() {
    println!("{key}: {value}");
}

let (first_key, first_value) = map.iter().next().unwrap();
assert_eq!((*first_key, *first_value), (1, "a"));
1.0.0 · Source

pub fn keys(&self) -> Keys<'_, K, V>

Gets an iterator over the keys of the map, in sorted order.

§Examples
use std::collections::BTreeMap;

let mut a = BTreeMap::new();
a.insert(2, "b");
a.insert(1, "a");

let keys: Vec<_> = a.keys().cloned().collect();
assert_eq!(keys, [1, 2]);
1.0.0 · Source

pub fn values(&self) -> Values<'_, K, V>

Gets an iterator over the values of the map, in order by key.

§Examples
use std::collections::BTreeMap;

let mut a = BTreeMap::new();
a.insert(1, "hello");
a.insert(2, "goodbye");

let values: Vec<&str> = a.values().cloned().collect();
assert_eq!(values, ["hello", "goodbye"]);
1.0.0 · Source

pub fn len(&self) -> usize

Returns the number of elements in the map.

§Examples
use std::collections::BTreeMap;

let mut a = BTreeMap::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);
1.0.0 · Source

pub fn is_empty(&self) -> bool

Returns true if the map contains no elements.

§Examples
use std::collections::BTreeMap;

let mut a = BTreeMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());
Source

pub fn lower_bound<Q>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
where K: Borrow<Q> + Ord, Q: Ord + ?Sized,

🔬This is a nightly-only experimental API. (btree_cursors)

Returns a Cursor pointing at the gap before the smallest key greater than the given bound.

Passing Bound::Included(x) will return a cursor pointing to the gap before the smallest key greater than or equal to x.

Passing Bound::Excluded(x) will return a cursor pointing to the gap before the smallest key greater than x.

Passing Bound::Unbounded will return a cursor pointing to the gap before the smallest key in the map.

§Examples
#![feature(btree_cursors)]

use std::collections::BTreeMap;
use std::ops::Bound;

let map = BTreeMap::from([
    (1, "a"),
    (2, "b"),
    (3, "c"),
    (4, "d"),
]);

let cursor = map.lower_bound(Bound::Included(&2));
assert_eq!(cursor.peek_prev(), Some((&1, &"a")));
assert_eq!(cursor.peek_next(), Some((&2, &"b")));

let cursor = map.lower_bound(Bound::Excluded(&2));
assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
assert_eq!(cursor.peek_next(), Some((&3, &"c")));

let cursor = map.lower_bound(Bound::Unbounded);
assert_eq!(cursor.peek_prev(), None);
assert_eq!(cursor.peek_next(), Some((&1, &"a")));
Source

pub fn upper_bound<Q>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
where K: Borrow<Q> + Ord, Q: Ord + ?Sized,

🔬This is a nightly-only experimental API. (btree_cursors)

Returns a Cursor pointing at the gap after the greatest key smaller than the given bound.

Passing Bound::Included(x) will return a cursor pointing to the gap after the greatest key smaller than or equal to x.

Passing Bound::Excluded(x) will return a cursor pointing to the gap after the greatest key smaller than x.

Passing Bound::Unbounded will return a cursor pointing to the gap after the greatest key in the map.

§Examples
#![feature(btree_cursors)]

use std::collections::BTreeMap;
use std::ops::Bound;

let map = BTreeMap::from([
    (1, "a"),
    (2, "b"),
    (3, "c"),
    (4, "d"),
]);

let cursor = map.upper_bound(Bound::Included(&3));
assert_eq!(cursor.peek_prev(), Some((&3, &"c")));
assert_eq!(cursor.peek_next(), Some((&4, &"d")));

let cursor = map.upper_bound(Bound::Excluded(&3));
assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
assert_eq!(cursor.peek_next(), Some((&3, &"c")));

let cursor = map.upper_bound(Bound::Unbounded);
assert_eq!(cursor.peek_prev(), Some((&4, &"d")));
assert_eq!(cursor.peek_next(), None);

Trait Implementations§

Source§

impl<P: Debug> Debug for Bill<P>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<P: Default> Default for Bill<P>

Source§

fn default() -> Bill<P>

Returns the “default value” for a type. Read more
Source§

impl<P: BillProduct> Deref for Bill<P>

Source§

type Target = BTreeMap<Tax, ItemList<P>>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &BTreeMap<Tax, ItemList<P>>

Dereferences the value.

Auto Trait Implementations§

§

impl<P> Freeze for Bill<P>

§

impl<P> RefUnwindSafe for Bill<P>
where P: RefUnwindSafe,

§

impl<P> Send for Bill<P>
where P: Send,

§

impl<P> Sync for Bill<P>
where P: Sync,

§

impl<P> Unpin for Bill<P>

§

impl<P> UnwindSafe for Bill<P>
where P: RefUnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.