Skip to main content

server/command/report/
size_order.rs

1use num_rational::Rational64;
2use num_traits::{CheckedAdd, CheckedSub};
3use std::cmp::Ordering;
4use std::collections::{BTreeMap, BTreeSet};
5
6/// Absolute value for ordering; any `i64::MIN` numerator has no positive counterpart and sorts as
7/// the largest.
8pub fn magnitude(v: Rational64) -> Rational64 {
9    if v >= Rational64::ZERO {
10        return v;
11    }
12    Rational64::ZERO
13        .checked_sub(&v)
14        .unwrap_or(Rational64::from_integer(i64::MAX))
15}
16
17fn size_by_symbol<'a>(amounts: &[(&'a str, Rational64)]) -> BTreeMap<&'a str, Rational64> {
18    let mut sizes = BTreeMap::new();
19    for (symbol, amount) in amounts {
20        let size = sizes.entry(*symbol).or_insert(Rational64::ZERO);
21        *size = size
22            .checked_add(&magnitude(*amount))
23            .unwrap_or(Rational64::from_integer(i64::MAX));
24    }
25    sizes
26}
27
28/// Ascending by size. Commodities are compared one by one in symbol order,
29/// a missing one counts as 0, and different commodities are never added.
30pub fn cmp_size(a: &[(&str, Rational64)], b: &[(&str, Rational64)]) -> Ordering {
31    let (left, right) = (size_by_symbol(a), size_by_symbol(b));
32    let symbols: BTreeSet<_> = left.keys().chain(right.keys()).copied().collect();
33    symbols
34        .into_iter()
35        .map(|s| {
36            let zero = Rational64::ZERO;
37            left.get(s)
38                .unwrap_or(&zero)
39                .cmp(right.get(s).unwrap_or(&zero))
40        })
41        .find(|o| o.is_ne())
42        .unwrap_or(Ordering::Equal)
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn the_magnitude_of_i64_min_is_the_largest_size_not_a_wrap() {
51        let min = Rational64::from_integer(i64::MIN);
52        assert_eq!(magnitude(min), Rational64::from_integer(i64::MAX));
53        assert_eq!(
54            cmp_size(&[("USD", min)], &[("USD", Rational64::from_integer(5))]),
55            Ordering::Greater
56        );
57    }
58}