okane-core 0.21.0

Library to support parsing, emitting and processing Ledger (https://www.ledger-cli.org/) format files.
Documentation
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Defines account and its related types.

use std::collections::{HashMap, hash_map};

use bumpalo::Bump;
use bumpalo_intern::direct::{
    DirectInternStore, FromInterned, InternedStr, OccupiedError, StoredValue,
};

/// Account which used in the Ledger format to store the balance with,
/// such as `Assets:Bank:Foo` or `Income:Salary`.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct Account<'arena>(InternedStr<'arena>);

impl<'arena> FromInterned<'arena> for Account<'arena> {
    fn from_interned(v: InternedStr<'arena>) -> Self {
        Self(v)
    }

    fn as_interned(&self) -> InternedStr<'arena> {
        self.0
    }
}

impl<'arena> Account<'arena> {
    /// Returns the `&str`.
    #[inline]
    pub fn as_str(&self) -> &'arena str {
        self.0.as_str()
    }
}

/// Manages [`Account`] instances.
pub struct AccountStore<'arena> {
    /// Interned Account store.
    intern: DirectInternStore<'arena, Account<'arena>>,
}

impl<'arena> AccountStore<'arena> {
    /// Creates a new instance.
    pub fn new(arena: &'arena Bump) -> Self {
        Self {
            intern: DirectInternStore::new(arena),
        }
    }

    /// Returns the [`Account`] with the given `value`,
    /// potentially resolving the alias.
    /// If not available, registers the given `value` as the canonical.
    pub fn ensure(&mut self, value: &str) -> Account<'arena> {
        self.intern.ensure(value)
    }

    /// Returns the Account with the given `value` if and only if it's already registered.
    pub fn resolve(&self, value: &str) -> Option<Account<'arena>> {
        self.intern.resolve(value)
    }

    /// Registers given `value` as always alias of `canonical`.
    /// Returns error if given `value` is already registered as canonical.
    pub fn register_alias(
        &mut self,
        value: &str,
        canonical: Account<'arena>,
    ) -> Result<(), OccupiedError<'arena, Account<'arena>>> {
        self.intern.register_alias(value, canonical)
    }

    /// Returns the [`Iterator`] for just `Account`.
    /// Order is unspecified.
    pub fn iter(&self) -> impl Iterator<Item = Account<'arena>> {
        self.intern.iter().filter_map(|v| match v {
            StoredValue::Alias { .. } => None,
            StoredValue::Canonical(a) => Some(a),
        })
    }
}

/// Represents not the [`Account`] itself, but rather a ancestor group which
/// itself is not an acount.
///
/// For example, if the Ledger has `Assets:Bank:Foo`, `Assets:Bank` or `Assets`
/// might be a [`AccountGroup`] if those don't appear as accounts.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct AccountAncestor<'arena>(InternedStr<'arena>);

impl<'arena> FromInterned<'arena> for AccountAncestor<'arena> {
    fn from_interned(v: InternedStr<'arena>) -> Self {
        Self(v)
    }

    fn as_interned(&self) -> InternedStr<'arena> {
        self.0
    }
}

/// Represents either an [`AccountAncestor`] or an [`Account`].
/// Useful for tree representation.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub enum AccountAggregate<'arena> {
    /// Concrete account which appeared in the Ledger file.
    Account(Account<'arena>),
    /// Ancestor of the tree acounts, which doesn't appear in the Ledger.
    Ancestor(AccountAncestor<'arena>),
}

impl<'arena> From<Account<'arena>> for AccountAggregate<'arena> {
    fn from(value: Account<'arena>) -> Self {
        Self::Account(value)
    }
}

impl<'arena> From<AccountAncestor<'arena>> for AccountAggregate<'arena> {
    fn from(value: AccountAncestor<'arena>) -> Self {
        Self::Ancestor(value)
    }
}

impl<'arena> AccountAggregate<'arena> {
    /// Returns the `&str` representation.
    #[inline]
    pub fn as_str(&self) -> &'arena str {
        match self {
            AccountAggregate::Account(Account(v)) => v.as_str(),
            AccountAggregate::Ancestor(AccountAncestor(v)) => v.as_str(),
        }
    }

    /// Returns the [`Account`] if this is an account, otherwise `None`.
    #[inline]
    pub fn as_account(&self) -> Option<Account<'arena>> {
        match self {
            AccountAggregate::Account(a) => Some(*a),
            AccountAggregate::Ancestor(_) => None,
        }
    }

    /// Returns the last colon-separated segment of the account name, i.e. the
    /// leaf label in a tree view (the whole name when there is no `:`).
    #[inline]
    pub fn last_segment(&self) -> &'arena str {
        let full = self.as_str();
        full.rsplit_once(':').map_or(full, |(_, leaf)| leaf)
    }
}

/// Represents the tree structure of the accounts, stored in the [`AccountStore`].
pub struct AccountTree<'arena> {
    prefixes: DirectInternStore<'arena, AccountAncestor<'arena>>,
    root_children: Vec<AccountAggregate<'arena>>,
    nodes: HashMap<AccountAggregate<'arena>, Node<'arena>>,
}

impl<'arena> AccountTree<'arena> {
    /// Creates a new instance.
    ///
    /// This constructs only a plain empty tree, and the actual work is done
    /// in [`Self::construct()`] because we want to retain the `prefixes`
    /// lifetime aligned with [`AccountStore`].
    pub fn new(arena: &'arena Bump) -> Self {
        Self {
            prefixes: DirectInternStore::new(arena),
            root_children: Vec::new(),
            nodes: HashMap::new(),
        }
    }

    /// Constructs the tree state from the given [`AccountStore`].
    pub fn construct(&mut self, accounts: &AccountStore<'arena>) {
        self.root_children.clear();
        self.nodes.clear();
        for account in accounts.iter() {
            if self.nodes.contains_key(&account.into()) {
                continue;
            }
            let mut current = AccountAggregate::Account(account);
            loop {
                let Some(parent) = self.ensure_parent(accounts, current) else {
                    // parent is root.
                    self.nodes.entry(current).or_insert_with(Node::placeholder);
                    self.root_children.push(current);
                    break;
                };
                let child_node = self.nodes.entry(current).or_insert_with(Node::placeholder);
                child_node.parent = AccountTreeKey::Descendant(parent);
                let (children, already_exists) = match self.nodes.entry(parent) {
                    hash_map::Entry::Occupied(existing) => {
                        (&mut existing.into_mut().children, true)
                    }
                    hash_map::Entry::Vacant(new) => {
                        (&mut new.insert(Node::placeholder()).children, false)
                    }
                };
                children.push(current);
                if already_exists {
                    break;
                };
                current = parent;
            }
        }
        self.root_children.sort_by_key(AccountAggregate::as_str);
        for node in self.nodes.values_mut() {
            node.children.sort_by_key(AccountAggregate::as_str);
        }
    }

    /// Ensures the parent of the given `child` account.
    /// Returns `None` if the parent is Root element of the tree.
    fn ensure_parent(
        &mut self,
        accounts: &AccountStore<'arena>,
        child: AccountAggregate<'arena>,
    ) -> Option<AccountAggregate<'arena>> {
        // if this is `None`, this means the given child is simple "Foo", and the parent is the root.
        let (parent, _) = child.as_str().rsplit_once(':')?;
        Some(match accounts.resolve(parent) {
            Some(v) => AccountAggregate::Account(v),
            None => AccountAggregate::Ancestor(self.prefixes.ensure(parent)),
        })
    }

    /// Resolves the [`AccountAncestor`] corresponding to the given `label`.
    /// Returns `None` if not found.
    /// Note that this would also return `None` if the given label is [`Account`].
    /// See [`super::ReportContext::account_aggregate()`], that is more convenient.
    pub fn resolve_ancestor(&self, label: &str) -> Option<AccountAncestor<'arena>> {
        self.prefixes.resolve(label)
    }

    /// Returns the parent of the given node.
    /// `None` if the given `account` is not found in the tree.
    pub fn parent<T: Into<AccountAggregate<'arena>>>(
        &self,
        account: T,
    ) -> Option<AccountTreeKey<'arena>> {
        self.nodes.get(&account.into()).map(|node| node.parent)
    }

    /// Returns the children of the given node.
    /// `None` if the given `key` is not found,
    /// and empty slice for the leaf account.
    pub fn children<T: Into<AccountTreeKey<'arena>>>(
        &self,
        key: T,
    ) -> Option<&[AccountAggregate<'arena>]> {
        match key.into() {
            AccountTreeKey::Root => Some(&self.root_children),
            AccountTreeKey::Descendant(account) => {
                self.nodes.get(&account).map(|n| n.children.as_slice())
            }
        }
    }
}

/// Key of the [`AccountTree`] which can be treated as a tree node.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub enum AccountTreeKey<'arena> {
    /// Root of the tree.
    Root,
    /// Non-root element of the tree.
    Descendant(AccountAggregate<'arena>),
}

impl<'arena> AccountTreeKey<'arena> {
    /// Returns as [`Option<AccountAggregate>`].
    /// It will be `Some` unless the self is root.
    #[inline]
    pub fn as_aggregate(self) -> Option<AccountAggregate<'arena>> {
        match self {
            Self::Root => None,
            Self::Descendant(a) => Some(a),
        }
    }
}

impl<'arena> From<Account<'arena>> for AccountTreeKey<'arena> {
    fn from(value: Account<'arena>) -> Self {
        Self::Descendant(value.into())
    }
}

impl<'arena> From<AccountAncestor<'arena>> for AccountTreeKey<'arena> {
    fn from(value: AccountAncestor<'arena>) -> Self {
        Self::Descendant(value.into())
    }
}

impl<'arena> From<AccountAggregate<'arena>> for AccountTreeKey<'arena> {
    fn from(value: AccountAggregate<'arena>) -> Self {
        Self::Descendant(value)
    }
}

/// Node of the [`AccountTree`].
#[derive(Debug, Clone)]
struct Node<'arena> {
    parent: AccountTreeKey<'arena>,
    children: Vec<AccountAggregate<'arena>>,
}

impl<'arena> Node<'arena> {
    /// Creates a place holder.
    fn placeholder() -> Self {
        Self {
            parent: AccountTreeKey::Root,
            children: Vec::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use pretty_assertions::assert_eq;

    #[test]
    fn account_aggregate_last_segment() {
        let arena = Bump::new();
        let mut accounts = AccountStore::new(&arena);
        let mut tree = AccountTree::new(&arena);
        let grocery = accounts.ensure("Expenses:Grocery");
        tree.construct(&accounts);
        let expenses = tree.resolve_ancestor("Expenses").unwrap();

        assert_eq!("Grocery", AccountAggregate::from(grocery).last_segment());
        assert_eq!("Expenses", AccountAggregate::from(expenses).last_segment());
    }

    mod account_tree {
        use super::assert_eq;
        use super::*;

        #[test]
        fn init_reuses_previous_value() {
            let arena = Bump::new();
            let mut accounts = AccountStore::new(&arena);
            let mut tree = AccountTree::new(&arena);

            let foo = accounts.ensure("Assets:Foo");
            tree.construct(&accounts);
            let assets = tree.parent(AccountAggregate::Account(foo)).unwrap();

            tree.construct(&accounts);
            let assets2 = tree.parent(AccountAggregate::Account(foo)).unwrap();

            assert_eq!(assets, assets2);
        }

        #[test]
        fn empty_tree() {
            let arena = Bump::new();
            let accounts = AccountStore::new(&arena);
            let mut tree = AccountTree::new(&arena);

            tree.construct(&accounts);

            assert!(tree.children(AccountTreeKey::Root).unwrap().is_empty());
        }

        #[test]
        fn tree_structure() {
            let arena = Bump::new();
            let mut accounts = AccountStore::new(&arena);

            let foo = accounts.ensure("Assets:Banks:Foo");
            let bar = accounts.ensure("Assets:Banks:Bar");
            let food = accounts.ensure("Expenses:Food");
            let food_special = accounts.ensure("Expenses:Food:Special");

            let mut tree = AccountTree::new(&arena);
            tree.construct(&accounts);

            let assets = tree.resolve_ancestor("Assets").unwrap();
            let banks = tree.resolve_ancestor("Assets:Banks").unwrap();
            let expenses = tree.resolve_ancestor("Expenses").unwrap();
            let parent_of: [(AccountTreeKey, AccountAggregate); _] = [
                (AccountTreeKey::Root, assets.into()),
                (AccountTreeKey::Root, expenses.into()),
                (assets.into(), banks.into()),
                (banks.into(), foo.into()),
                (banks.into(), bar.into()),
                (expenses.into(), food.into()),
                (food.into(), food_special.into()),
            ];
            for (expected, child) in parent_of {
                assert_eq!(expected, tree.parent(child).unwrap());
            }
            let children_of: [(&[AccountAggregate], AccountTreeKey); _] = [
                (
                    &[
                        AccountAggregate::Ancestor(assets),
                        AccountAggregate::Ancestor(expenses),
                    ],
                    AccountTreeKey::Root,
                ),
                (&[AccountAggregate::Ancestor(banks)], assets.into()),
                (
                    // alphabetically sorted.
                    &[
                        AccountAggregate::Account(bar),
                        AccountAggregate::Account(foo),
                    ],
                    banks.into(),
                ),
                (&[AccountAggregate::Account(food)], expenses.into()),
                (&[AccountAggregate::Account(food_special)], food.into()),
            ];
            for (expected, parent) in children_of {
                assert_eq!(expected, tree.children(parent).unwrap());
            }
        }
    }
}