okane-core 0.19.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
use std::{
    collections::{BTreeMap, btree_map},
    fmt::Display,
    iter::FusedIterator,
    ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign},
};

use rust_decimal::Decimal;

use crate::report::{
    commodity::{CommodityStore, CommodityTag},
    context::ReportContext,
};

use super::{PostingAmount, SingleAmount, error::EvalError};

/// Amount with multiple commodities, or simple zero.
#[derive(Debug, Default, PartialEq, Eq, Clone)]
pub struct Amount<'ctx> {
    // if values.len == zero, then it'll be completely zero.
    // TODO: Consider optimizing for small number of commodities,
    // as most of the case it needs to be just a few elements.
    values: BTreeMap<CommodityTag<'ctx>, Decimal>,
}

impl<'ctx> TryFrom<Amount<'ctx>> for SingleAmount<'ctx> {
    type Error = EvalError<'ctx>;

    fn try_from(value: Amount<'ctx>) -> Result<Self, Self::Error> {
        SingleAmount::try_from(&value)
    }
}

impl<'ctx> TryFrom<Amount<'ctx>> for PostingAmount<'ctx> {
    type Error = EvalError<'ctx>;

    fn try_from(value: Amount<'ctx>) -> Result<Self, Self::Error> {
        PostingAmount::try_from(&value)
    }
}

impl<'ctx> TryFrom<&Amount<'ctx>> for SingleAmount<'ctx> {
    type Error = EvalError<'ctx>;

    fn try_from(value: &Amount<'ctx>) -> Result<Self, Self::Error> {
        let (commodity, value) = value
            .values
            .iter()
            .next()
            .ok_or(EvalError::SingleAmountRequired)?;
        Ok(SingleAmount {
            value: *value,
            commodity: *commodity,
        })
    }
}

impl<'ctx> TryFrom<&Amount<'ctx>> for PostingAmount<'ctx> {
    type Error = EvalError<'ctx>;

    fn try_from(value: &Amount<'ctx>) -> Result<Self, Self::Error> {
        if value.values.len() > 1 {
            Err(EvalError::PostingAmountRequired)
        } else {
            Ok(value
                .values
                .iter()
                .next()
                .map(|(commodity, value)| {
                    PostingAmount::Single(SingleAmount {
                        value: *value,
                        commodity: *commodity,
                    })
                })
                .unwrap_or_default())
        }
    }
}

impl<'ctx> From<PostingAmount<'ctx>> for Amount<'ctx> {
    fn from(value: PostingAmount<'ctx>) -> Self {
        match value {
            PostingAmount::Zero => Amount::zero(),
            PostingAmount::Single(single_amount) => single_amount.into(),
        }
    }
}

impl<'ctx> From<SingleAmount<'ctx>> for Amount<'ctx> {
    fn from(value: SingleAmount<'ctx>) -> Self {
        Amount::from_value(value.commodity, value.value)
    }
}

impl<'ctx> FromIterator<(CommodityTag<'ctx>, Decimal)> for Amount<'ctx> {
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = (CommodityTag<'ctx>, Decimal)>,
    {
        let mut ret = Self::zero();
        for (commodity, value) in iter.into_iter() {
            ret += SingleAmount::from_value(commodity, value);
        }
        ret
    }
}

impl<'ctx> Amount<'ctx> {
    /// Creates an [`Amount`] with zero value.
    #[inline(always)]
    pub fn zero() -> Self {
        Self::default()
    }

    /// Creates an [`Amount`] with single value and commodity.
    pub fn from_value(commodity: CommodityTag<'ctx>, amount: Decimal) -> Self {
        Self::zero() + SingleAmount::from_value(commodity, amount)
    }

    /// Creates an [`Amount`] from a set of values in [`BTreeMap`].
    pub fn from_values(values: BTreeMap<CommodityTag<'ctx>, Decimal>) -> Self {
        Self { values }
    }

    /// Takes out the instance and returns map from commodity to its value.
    pub fn into_values(self) -> BTreeMap<CommodityTag<'ctx>, Decimal> {
        self.values
    }

    /// Returns an iterator over its amount.
    pub fn iter(&self) -> impl Iterator<Item = SingleAmount<'ctx>> + '_ {
        AmountIter(self.values.iter())
    }

    /// Returns an object to print the amount as inline.
    ///
    /// The commodity is ordered by the appearing order, and deterministic.
    pub fn as_inline_display<'a>(&'a self, ctx: &'a ReportContext<'ctx>) -> impl Display + 'a + 'ctx
    where
        'a: 'ctx,
    {
        InlinePrintAmount {
            commodity_store: &ctx.commodities,
            amount: self,
        }
    }

    /// Returns `true` if this is 'non-commoditized zero', which is used to assert
    /// the account balance is completely zero.
    pub fn is_absolute_zero(&self) -> bool {
        self.values.is_empty()
    }

    /// Returns `true` if this is zero, including zero commodities.
    pub fn is_zero(&self) -> bool {
        self.values.iter().all(|(_, v)| v.is_zero())
    }

    /// Removes zero values, useful when callers doesn't care zero value.
    /// However, if caller must distinguish `0` and `0 commodity`,
    /// caller must not use this method.
    pub fn remove_zero_entries(&mut self) {
        self.values.retain(|_, v| !v.is_zero());
    }

    /// Replace the amount of the particular commodity, and returns the previous amount for the commodity.
    /// E.g. (100 USD + 100 EUR).set_partial(200, USD) returns 100.
    /// Note this method removes the given commodity if value is zero,
    /// so only meant for [`Balance`].
    pub(crate) fn set_partial(&mut self, amount: SingleAmount<'ctx>) -> SingleAmount<'ctx> {
        let value = if amount.value.is_zero() {
            self.values.remove(&amount.commodity)
        } else {
            self.values.insert(amount.commodity, amount.value)
        }
        .unwrap_or_default();
        SingleAmount {
            value,
            commodity: amount.commodity,
        }
    }

    /// Returns the amount of the particular commodity.
    fn get_part(&self, commodity: CommodityTag<'ctx>) -> Decimal {
        self.values.get(&commodity).copied().unwrap_or_default()
    }

    /// Returns pair of commodity amount, if the amount contains exactly 2 commodities.
    /// Otherwise returns None.
    pub fn maybe_pair(&self) -> Option<(SingleAmount<'ctx>, SingleAmount<'ctx>)> {
        if self.values.len() != 2 {
            return None;
        }
        let ((c1, v1), (c2, v2)) = self.values.iter().zip(self.values.iter().skip(1)).next()?;
        Some((
            SingleAmount::from_value(*c1, *v1),
            SingleAmount::from_value(*c2, *v2),
        ))
    }

    /// Rounds the given Amount and returns the new instance.
    pub fn round(mut self, ctx: &ReportContext) -> Self {
        self.round_mut(ctx);
        self
    }

    /// Rounds the Amount in-place with the given context provided precision.
    pub fn round_mut(&mut self, ctx: &ReportContext) {
        for (k, v) in self.values.iter_mut() {
            match ctx.commodities.get_decimal_point(*k) {
                None => (),
                Some(dp) => {
                    let updated = v.round_dp_with_strategy(
                        dp,
                        rust_decimal::RoundingStrategy::MidpointNearestEven,
                    );
                    *v = updated;
                }
            }
        }
    }

    /// Creates negated instance.
    pub fn negate(mut self) -> Self {
        for (_, v) in self.values.iter_mut() {
            v.set_sign_positive(!v.is_sign_positive())
        }
        self
    }

    /// Run division with error checking.
    pub fn check_div(mut self, rhs: Decimal) -> Result<Self, EvalError<'ctx>> {
        if rhs.is_zero() {
            return Err(EvalError::DivideByZero);
        }
        for (_, v) in self.values.iter_mut() {
            *v = v.checked_div(rhs).ok_or(EvalError::NumberOverflow)?;
        }
        Ok(self)
    }

    /// Checks if the amount is matching with the given [`PostingAmount`] balance,
    /// Returns the diff (expected - actual), or None if those are consistent.
    ///
    /// Consistent means
    ///
    /// *   If the given balance is zero, then the amount must be zero.
    /// *   If the given balance is a value with commodity,
    ///     then the amount should be equal to given value only on the commodity.
    pub(crate) fn assert_balance(&self, expected: &PostingAmount<'ctx>) -> Self {
        match expected {
            PostingAmount::Zero => {
                if self.is_zero() {
                    Self::zero()
                } else {
                    -self.clone()
                }
            }
            PostingAmount::Single(single) => {
                let diff = single.value - self.get_part(single.commodity);
                if diff.is_zero() {
                    Self::zero()
                } else {
                    Self::from_value(single.commodity, diff)
                }
            }
        }
    }
}

#[derive(Debug)]
struct AmountIter<'a, 'ctx>(btree_map::Iter<'a, CommodityTag<'ctx>, Decimal>);

impl<'ctx> Iterator for AmountIter<'_, 'ctx> {
    type Item = SingleAmount<'ctx>;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|(c, v)| SingleAmount::from_value(*c, *v))
    }
}

impl FusedIterator for AmountIter<'_, '_> {}

#[derive(Debug)]
struct InlinePrintAmount<'a, 'ctx> {
    commodity_store: &'a CommodityStore<'ctx>,
    amount: &'a Amount<'ctx>,
}

impl Display for InlinePrintAmount<'_, '_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let vs = &self.amount.values;
        if vs.len() <= 1 {
            return match vs.iter().next() {
                Some((c, v)) => {
                    write!(f, "{} {}", v, c.to_str_lossy(self.commodity_store))
                }
                None => write!(f, "0"),
            };
        }
        // wrap in () for 2 or more commodities case.
        write!(f, "(")?;
        for (i, (c, v)) in vs.iter().enumerate() {
            let mut v = *v;
            if i != 0 {
                if v.is_sign_negative() {
                    v.set_sign_negative(false);
                    write!(f, " - ")?;
                } else {
                    write!(f, " + ")?;
                }
            }
            write!(f, "{} {}", v, c.to_str_lossy(self.commodity_store))?;
        }
        write!(f, ")")
    }
}

impl Neg for Amount<'_> {
    type Output = Self;

    fn neg(self) -> Self::Output {
        self.negate()
    }
}

impl Add for Amount<'_> {
    type Output = Self;

    fn add(mut self, rhs: Self) -> Self::Output {
        self += rhs;
        self
    }
}

impl AddAssign for Amount<'_> {
    fn add_assign(&mut self, rhs: Self) {
        for (c, v2) in rhs.values {
            let mut v1 = self.values.entry(c).or_insert(Decimal::ZERO);
            v1 += v2;
            // we should retain the value even if zero,
            // as (0 USD + 0 EUR) are different from 0 or (0 USD + 0 USD).
        }
    }
}

impl<'ctx> Add<SingleAmount<'ctx>> for Amount<'ctx> {
    type Output = Amount<'ctx>;

    fn add(mut self, rhs: SingleAmount<'ctx>) -> Self::Output {
        self += rhs;
        self
    }
}

impl<'ctx> AddAssign<SingleAmount<'ctx>> for Amount<'ctx> {
    fn add_assign(&mut self, rhs: SingleAmount<'ctx>) {
        let curr = self.values.entry(rhs.commodity).or_default();
        *curr += rhs.value;
    }
}

impl<'ctx> AddAssign<PostingAmount<'ctx>> for Amount<'ctx> {
    fn add_assign(&mut self, rhs: PostingAmount<'ctx>) {
        match rhs {
            PostingAmount::Zero => (),
            PostingAmount::Single(single) => *self += single,
        }
    }
}

impl Sub for Amount<'_> {
    type Output = Self;

    fn sub(mut self, rhs: Self) -> Self::Output {
        self -= rhs;
        self
    }
}

impl SubAssign for Amount<'_> {
    fn sub_assign(&mut self, rhs: Self) {
        for (c, v2) in rhs.values {
            let mut v1 = self.values.entry(c).or_insert(Decimal::ZERO);
            v1 -= v2;
        }
    }
}

impl Mul<Decimal> for Amount<'_> {
    type Output = Self;

    fn mul(mut self, rhs: Decimal) -> Self::Output {
        self *= rhs;
        self
    }
}

impl MulAssign<Decimal> for Amount<'_> {
    fn mul_assign(&mut self, rhs: Decimal) {
        for (_, mut v) in self.values.iter_mut() {
            v *= rhs;
        }
    }
}

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

    use bumpalo::Bump;
    use maplit::btreemap;
    use pretty_assertions::assert_eq;
    use pretty_decimal::PrettyDecimal;
    use rust_decimal_macros::dec;

    use crate::report::ReportContext;

    #[test]
    fn test_default() {
        let arena = Bump::new();
        let ctx = ReportContext::new(&arena);
        let amount = Amount::default();
        assert_eq!(format!("{}", amount.as_inline_display(&ctx)), "0")
    }

    #[test]
    fn test_from_value() {
        let arena = Bump::new();
        let mut ctx = ReportContext::new(&arena);
        let jpy = ctx.commodities.ensure("JPY");
        let amount = Amount::from_value(jpy, dec!(123.45));
        assert_eq!(format!("{}", amount.as_inline_display(&ctx)), "123.45 JPY")
    }

    #[test]
    fn test_from_values() {
        let arena = Bump::new();
        let mut ctx = ReportContext::new(&arena);
        let jpy = ctx.commodities.ensure("JPY");
        let chf = ctx.commodities.ensure("CHF");

        let amount = Amount::from_iter([(jpy, dec!(10)), (chf, dec!(1))]);
        assert_eq!(
            amount.into_values(),
            btreemap! {jpy => dec!(10), chf => dec!(1)},
        );

        let amount = Amount::from_iter([(jpy, dec!(10)), (jpy, dec!(1))]);
        assert_eq!(amount.into_values(), btreemap! {jpy => dec!(11)});

        let amount = Amount::from_iter([(jpy, dec!(10)), (jpy, dec!(-10))]);
        assert_eq!(amount.into_values(), btreemap! {jpy => dec!(0)});
    }

    #[test]
    fn test_is_absolute_zero() {
        let arena = Bump::new();
        let mut ctx = ReportContext::new(&arena);
        let jpy = ctx.commodities.ensure("JPY");
        let usd = ctx.commodities.ensure("USD");

        assert!(Amount::default().is_absolute_zero());
        assert!(!Amount::from_value(jpy, dec!(0)).is_absolute_zero());

        let mut amount = Amount::from_iter([(jpy, dec!(0)), (usd, dec!(0))]);
        assert!(
            !amount.is_absolute_zero(),
            "{}",
            amount.as_inline_display(&ctx)
        );

        amount.remove_zero_entries();
        assert!(
            amount.is_absolute_zero(),
            "{}",
            amount.as_inline_display(&ctx)
        );
    }

    #[test]
    fn test_is_zero() {
        let arena = Bump::new();
        let mut ctx = ReportContext::new(&arena);
        let jpy = ctx.commodities.ensure("JPY");
        let usd = ctx.commodities.ensure("USD");

        assert!(Amount::default().is_zero());
        assert!(Amount::from_value(jpy, dec!(0)).is_zero());
        assert!(Amount::from_iter([(jpy, dec!(0)), (usd, dec!(0))]).is_zero());

        assert!(!Amount::from_value(jpy, dec!(1)).is_zero());
        assert!(!Amount::from_iter([(jpy, dec!(0)), (usd, dec!(1))]).is_zero());
    }

    #[test]
    fn test_neg() {
        let arena = Bump::new();
        let mut ctx = ReportContext::new(&arena);
        let jpy = ctx.commodities.ensure("JPY");
        let usd = ctx.commodities.ensure("USD");

        assert_eq!(-Amount::zero(), Amount::zero());
        assert_eq!(
            -Amount::from_value(jpy, dec!(100)),
            Amount::from_value(jpy, dec!(-100))
        );
        assert_eq!(
            -Amount::from_iter([(jpy, dec!(100)), (usd, dec!(-20.35))]),
            Amount::from_iter([(jpy, dec!(-100)), (usd, dec!(20.35))]),
        );
    }

    #[test]
    fn test_add_amount() {
        let arena = Bump::new();
        let mut ctx = ReportContext::new(&arena);
        let jpy = ctx.commodities.ensure("JPY");
        let usd = ctx.commodities.ensure("USD");
        let eur = ctx.commodities.ensure("EUR");
        let chf = ctx.commodities.ensure("CHF");

        let zero_plus_zero = Amount::zero() + Amount::zero();
        assert_eq!(zero_plus_zero, Amount::zero());

        assert_eq!(
            Amount::from_value(jpy, dec!(1)) + Amount::zero(),
            Amount::from_value(jpy, dec!(1)),
        );
        assert_eq!(
            Amount::zero() + Amount::from_value(jpy, dec!(1)),
            Amount::from_value(jpy, dec!(1)),
        );
        assert_eq!(
            Amount::from_iter([
                (jpy, dec!(123.00)),
                (usd, dec!(456.0)),
                (eur, dec!(7.89)),
                (chf, dec!(0)), // 0 CHF retained
            ]),
            Amount::from_value(jpy, dec!(123.45))
                + Amount::from_value(jpy, dec!(-0.45))
                + Amount::from_value(usd, dec!(456))
                + Amount::from_value(usd, dec!(0.0))
                + -Amount::from_value(chf, dec!(100))
                + Amount::from_value(eur, dec!(7.89))
                + Amount::from_value(chf, dec!(100)),
        );

        assert_eq!(
            Amount::from_iter([(jpy, dec!(0)), (usd, dec!(0)), (chf, dec!(0))]),
            Amount::from_iter([(jpy, dec!(1)), (usd, dec!(2)), (chf, dec!(3))])
                + Amount::from_iter([(jpy, dec!(-1)), (usd, dec!(-2)), (chf, dec!(-3))])
        );
    }

    #[test]
    fn test_add_single_amount() {
        let arena = Bump::new();
        let mut ctx = ReportContext::new(&arena);
        let jpy = ctx.commodities.ensure("JPY");
        let usd = ctx.commodities.ensure("USD");

        let amount = Amount::zero() + SingleAmount::from_value(usd, dec!(0));
        assert_eq!(amount, Amount::from_value(usd, dec!(0)));

        assert_eq!(
            Amount::zero() + SingleAmount::from_value(jpy, dec!(1)),
            Amount::from_value(jpy, dec!(1)),
        );
    }

    #[test]
    fn test_sub() {
        let arena = Bump::new();
        let mut ctx = ReportContext::new(&arena);
        let jpy = ctx.commodities.ensure("JPY");
        let usd = ctx.commodities.ensure("USD");
        let eur = ctx.commodities.ensure("EUR");
        let chf = ctx.commodities.ensure("CHF");

        let zero_minus_zero = Amount::zero() - Amount::zero();
        assert_eq!(zero_minus_zero, Amount::zero());

        assert_eq!(
            Amount::from_value(jpy, dec!(1)) - Amount::zero(),
            Amount::from_value(jpy, dec!(1)),
        );
        assert_eq!(
            Amount::zero() - Amount::from_value(jpy, dec!(1)),
            Amount::from_value(jpy, dec!(-1)),
        );
        assert_eq!(
            Amount::from_iter([
                (jpy, dec!(12345)),
                (eur, dec!(-200)),
                (chf, dec!(13.3)),
                (usd, dec!(0))
            ]),
            Amount::from_iter([(jpy, dec!(12345)), (usd, dec!(56.78))])
                - Amount::from_iter([(usd, dec!(56.780)), (eur, dec!(200)), (chf, dec!(-13.3)),]),
        );
    }

    fn eps() -> Decimal {
        Decimal::try_from_i128_with_scale(1, 28).unwrap()
    }

    #[test]
    fn test_mul() {
        let arena = Bump::new();
        let mut ctx = ReportContext::new(&arena);
        let jpy = ctx.commodities.ensure("JPY");
        let eur = ctx.commodities.ensure("EUR");
        let chf = ctx.commodities.ensure("CHF");

        assert_eq!(Amount::zero() * dec!(5), Amount::zero());
        assert_eq!(
            Amount::from_value(jpy, dec!(1)) * Decimal::ZERO,
            Amount::from_value(jpy, dec!(0)),
        );
        assert_eq!(
            Amount::from_value(jpy, dec!(123)) * dec!(3),
            Amount::from_value(jpy, dec!(369)),
        );
        assert_eq!(
            Amount::from_iter([(jpy, dec!(10081)), (eur, dec!(200)), (chf, dec!(-13.3))])
                * dec!(-0.5),
            Amount::from_iter([(jpy, dec!(-5040.5)), (eur, dec!(-100.0)), (chf, dec!(6.65))]),
        );
        assert_eq!(
            Amount::from_value(jpy, eps()) * eps(),
            Amount::from_value(jpy, dec!(0))
        );
    }

    #[test]
    fn test_check_div() {
        let arena = Bump::new();
        let mut ctx = ReportContext::new(&arena);
        let jpy = ctx.commodities.ensure("JPY");
        let eur = ctx.commodities.ensure("EUR");
        let chf = ctx.commodities.ensure("CHF");

        assert_eq!(Amount::zero().check_div(dec!(5)).unwrap(), Amount::zero());
        assert_eq!(
            Amount::zero().check_div(dec!(0)).unwrap_err(),
            EvalError::DivideByZero
        );

        assert_eq!(
            Amount::from_value(jpy, dec!(50))
                .check_div(dec!(4))
                .unwrap(),
            Amount::from_value(jpy, dec!(12.5))
        );

        assert_eq!(
            Amount::from_value(jpy, Decimal::MAX)
                .check_div(eps())
                .unwrap_err(),
            EvalError::NumberOverflow
        );

        assert_eq!(
            Amount::from_value(jpy, eps())
                .check_div(Decimal::MAX)
                .unwrap(),
            Amount::from_value(jpy, dec!(0))
        );

        assert_eq!(
            Amount::from_iter([(jpy, dec!(810)), (eur, dec!(-100.0)), (chf, dec!(6.66))])
                .check_div(dec!(3))
                .unwrap(),
            Amount::from_iter([
                (jpy, dec!(270)),
                (eur, dec!(-33.333333333333333333333333333)),
                (chf, dec!(2.22))
            ]),
        );
    }

    #[test]
    fn test_round() {
        let arena = Bump::new();
        let mut ctx = ReportContext::new(&arena);
        let jpy = ctx.commodities.ensure("JPY");
        let eur = ctx.commodities.ensure("EUR");
        let chf = ctx.commodities.ensure("CHF");

        ctx.commodities
            .set_format(jpy, PrettyDecimal::comma3dot(dec!(12345)));
        ctx.commodities
            .set_format(eur, PrettyDecimal::plain(dec!(123.45)));
        ctx.commodities
            .set_format(chf, PrettyDecimal::comma3dot(dec!(123.450)));

        assert_eq!(Amount::zero(), Amount::zero().round(&ctx));

        assert_eq!(
            Amount::from_iter([(jpy, dec!(812)), (eur, dec!(-100.00)), (chf, dec!(6.660))]),
            Amount::from_iter([(jpy, dec!(812)), (eur, dec!(-100.0)), (chf, dec!(6.66))])
                .round(&ctx),
        );

        assert_eq!(
            Amount::from_iter([(jpy, dec!(812)), (eur, dec!(-100.02)), (chf, dec!(6.666))]),
            Amount::from_iter([
                (jpy, dec!(812.5)),
                (eur, dec!(-100.015)),
                (chf, dec!(6.6665))
            ])
            .round(&ctx),
        );
    }

    #[test]
    fn test_to_string() {
        let arena = Bump::new();
        let mut ctx = ReportContext::new(&arena);
        let jpy = ctx.commodities.ensure("JPY");
        let chf = ctx.commodities.ensure("CHF");

        assert_eq!("0", Amount::default().as_inline_display(&ctx).to_string());

        assert_eq!(
            "10 JPY",
            Amount::from_value(jpy, dec!(10))
                .as_inline_display(&ctx)
                .to_string()
        );

        assert_eq!(
            "(10 JPY + 1 CHF)",
            Amount::from_iter([(jpy, dec!(10)), (chf, dec!(1))])
                .as_inline_display(&ctx)
                .to_string()
        );

        assert_eq!(
            "(-10 JPY - 1 CHF)",
            Amount::from_iter([(jpy, dec!(-10)), (chf, dec!(-1))])
                .as_inline_display(&ctx)
                .to_string()
        );
    }
}