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
use crate::account::{Account, AccountId};
use std::collections::hash_map::Entry;
use std::collections::HashMap;
#[derive(Debug)]
pub struct AccountRepository {
account_map: HashMap<String, AccountId>,
accounts: Vec<Account>,
}
impl AccountRepository {
pub fn new() -> Self {
Self {
accounts: vec![],
account_map: HashMap::new(),
}
}
pub fn account_iter(&self) -> impl Iterator<Item = &Account> {
self.accounts.iter()
}
pub fn lookup_by_fullname(&self, account_name: &str) -> Option<&Account> {
self.account_map
.get(account_name)
.map(|&AccountId(idx)| &self.accounts[idx])
}
pub fn lookup_by_fullname_mut(&mut self, account_name: &str) -> Option<&mut Account> {
match self.account_map.get(account_name) {
Some(&AccountId(idx)) => Some(&mut self.accounts[idx]),
None => None,
}
}
pub fn add(&mut self, account: Account) -> Result<AccountId, ()> {
match self.account_map.entry(account.fullname.clone()) {
Entry::Vacant(vacant) => {
let idx = AccountId(self.accounts.len());
vacant.insert(idx);
self.accounts.push(account);
Ok(idx)
}
Entry::Occupied(_) => Err(()),
}
}
}
#[test]
fn it_should_correctly_lookup_account_by_fullname() {
let mut repo = AccountRepository::new();
repo.add(Account {
fullname: "Expenses:IceCream".into(),
partname: "IceCream".into(),
balance: 0.into(),
commodity: None,
child_accounts: vec![],
})
.unwrap();
repo.add(Account {
fullname: "Expenses:IceCream2".into(),
partname: "IceCream2".into(),
balance: 0.into(),
commodity: None,
child_accounts: vec![],
})
.unwrap();
assert_eq!(
Some("IceCream"),
repo.lookup_by_fullname("Expenses:IceCream")
.map(|acct| acct.partname.as_str())
);
assert_eq!(
Some("IceCream2"),
repo.lookup_by_fullname("Expenses:IceCream2")
.map(|acct| acct.partname.as_str())
);
assert_eq!(
None,
repo.lookup_by_fullname("Expenses:IceCream3")
.map(|acct| acct.partname.as_str())
);
}