ledger_utils/
tree_balance.rs

1use crate::account_balance::AccountBalance;
2use crate::balance::Balance;
3use std::collections::HashMap;
4
5/// Balance of one or more accounts.
6/// Converted to a tree.
7#[derive(Debug, Clone)]
8pub struct TreeBalanceNode {
9    pub balance: AccountBalance,
10    pub children: HashMap<String, TreeBalanceNode>,
11}
12
13impl TreeBalanceNode {
14    pub fn new() -> Self {
15        TreeBalanceNode {
16            balance: AccountBalance::new(),
17            children: HashMap::new(),
18        }
19    }
20}
21
22impl Default for TreeBalanceNode {
23    fn default() -> Self {
24        Self::new()
25    }
26}
27
28impl From<Balance> for TreeBalanceNode {
29    fn from(balance: Balance) -> Self {
30        let mut root = TreeBalanceNode::new();
31
32        for (account_name, account_balance) in balance.account_balances {
33            let path = account_name.split(':');
34            let mut node = &mut root;
35            node.balance += &account_balance;
36
37            for path_part in path {
38                node = node.children.entry(path_part.to_string()).or_default();
39                node.balance += &account_balance;
40            }
41        }
42
43        root
44    }
45}